이번 챕터의 목적


JDK5 부터 사용가능해진 제네릭(generic)은 불필요한 형변환 작업을 생략하게 해주고, 사용자 입장에서 한결 편하게 타입추론이 가능하게 해주는 기능이다. 제네릭을 사용하면 컬렉션이 담을 수 있는 타입을 컴파일러에게 알려주게 되기에, 컴파일러는 알아서 형변환 코드를 추가할 수 있게 되고, 애초에 컴파일 과정에서부터 잘못된 타입의 객체를 넣지 못하게 차단해서 안전하고 명확한 코드를 작성할 수 있다.

이번 장에서는 이런 제네릭의 이점을 최대로 살리고 단점을 최소화하는 방법에 대해 이야기해본다.

Previous


이번 챕터 전반에 사용되는 지네릭스 용어에 대해 설명한다.

$\begin{array}{|c|c|c|c|}\hline \textbf{한글용어}&\textbf{영문 용어}&\textbf{예}&\textbf{아이템}\\\hline \text{매개변수화 타입}&\text{parameterized type}&\text{List<String>}&\text{26}\\\hline \text{실제 타입매개변수}&\text{actual type parameter}&\text{String}&\text{26}\\\hline \text{제네릭 타입}&\text{generic type}&\text{List<E>}&\text{26, 29}\\\hline \text{정규 타입 매개변수}&\text{formal type parameter}&\text{E}&\text{26}\\\hline \text{비한정적 와일드카드 타입}&\text{unbounded wildcard type}&\text{List<?>}&\text{26}\\\hline \text{로 타입}&\text{raw type}&\text{List}&\text{26}\\\hline \text{한정적 타입 매개변수}&\text{bounded type parameter}&\text{<E extends Number>}&\text{29}\\\hline \text{재귀적 타입 한정}&\text{recursive type bound}&\text{<T extends Comparable<T>>}&\text{30}\\\hline \text{한정적 와일드카드 타입}&\text{bounded wildcard type}&\text{List<? extends Number>}&\text{31}\\\hline \text{제네릭 메서드}&\text{generic method}&\text{static <E> List<E> asList(E[] a)}&\text{30}\\\hline \text{타입 토큰}&\text{type token}&\text{String.class}&\text{33}\\\hline \end{array}$

26. 로 타입은 사용하지 말라


previous

제네릭 클래스(or 제네릭 인터페이스)

:클래스와 인터페이스 선언에 타입 매개변수(type parameter)가 쓰인 클래스 혹은 인터페이스 (Ex: List<E>, Set<E>, Map<K, V>)로 이를 통틀어 제네릭 타입(generic type)이라 한다.

제네릭 타입은 매개변수화 타입(parameterized type)을 정의하는데 이 타입이 정규 타입 매개변수에 해당하는 실제 타입 매개변수가 된다. 다음 코드를 보자.

public interface List<E> extends Collection<E> { ... }
...
private final List<String> = ...;