제네릭 타입 (Generic Types)
- 제네릭 타입은 타입 파라미터를 가지는 제네릭 클래스 혹은 제네릭 인터페이스이다.
/** * Generic version of the Box class. * @param <T> the type of the value being boxed */ public class Box<T> { // T stands for "Type" private T t; public void set(T t) { this.t = t; } public T get() { return t; } }
제네릭 타입은 any non-primitive 한 타입이 될 수 있다. (annotation 은 안됨)
i.e.) any class type, any interface type, any array type, or enum type
타입 파라미터 네이밍 컨벤션
The most commonly used type parameter names are:
- E - Element (used extensively by the Java Collections Framework)
- K - Key
- N - Number
- T - Type
- V - Value
- S,U,V etc. - 2nd, 3rd, 4th types
제네릭 타입을 선언, 생성하는 방법
Box<Integer> integerBox = new Box<Integer>();
Box<Integer> integerBox = new Box< >();
- 다이아몬드 연산자를 통해 생성시의 타입 인자를 생략할 수 있음 (컴파일러의 타입 추론)
다양한 방식의 제네릭 타입 선언
- Multiple Type Parameters
public interface Pair<K, V> { public K getKey(); public V getValue(); } public class OrderedPair<K, V> implements Pair<K, V> { private K key; private V value; public OrderedPair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } }
- Parameterized Types
OrderedPair<String, Box<Integer>> p = new OrderedPair<>("primes", new Box<>(...));
로 타입 (Raw Types)
로 타입이란 타입 인자 없이 선언된 제네릭 클래스 혹은 인터페이스이다.
Box rawBox = new Box();
타입 인자의 명시적 표시 혹은 컴파일러가 추론하기 위한 다이아몬드 연산자 모두 없음 → 로 타입!
JDK 5.0이전의 레거시 코드에는 간간히 로 타입을 활용한 코드가 보인다 (Collections)
- 로 타입으로 선언하면
- 개별 인스턴스는 타입 인자로
Object
가 전달된 것 처럼 동작한다. - 즉 rawBox 는 아무 객체 (Object)를 전달 받을 수 있다.
- 하지만 Object 를 명시적으로 표현해 주는 것과는 compatibility 측면에서 차이가 있다.

- 자세한 내용은 아래 Erasure 에서 다루겠다.
- 로 타입을 사용하면
- 컴파일러는 경고로그를 발생시킨다.
Note: Example.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
- 경고를 없애고 싶다면 로 타입 선언시
@SuppressWarnings
어노테이션을 달아주자