필드에서 데이터 타입을 확정 시키고 싶지 않을 때 사용한다.
클래스 내부에서 사용할 데이터 타입을 외부에서 지정하는 기법이다.

위의 코드르 봤을 때, Person 이라는 클래스의 매개변수가 기본 자료형이 아닌 T로 표기되어 있다. 생성자를 생성할 때 원하는 자료형을 사용할 수 있도록 하는 것이 제네릭이다.
기본 데이터 타입을 그냥 바로 사용할 수 없다. 무슨 뜻인지 코드를 통해 보고자 한다.
class EmployeeInfo{
public int rank;
EmployeeInfo(int rank){
this.rank = rank;
}
}
class Person<T, S>{
public T info;
public S id;
Person(T info, S id){
this.info = info;
this.id = id;
}
}
public class GenericDemo {
public static void main(String[] args) {
Person<EmployeeInfo, int> p1 = new Person<EmployeeInfo, int> (new EmployeeInfo(1), 1);
}
}
다음과 같이 코드를 작성하면 Person이라는 p1 인스턴스를 생성할 때 int 로 인해 오류가 발생한다.
제네릭에선 기본 자료형을 바로 사용할 수 없으며, 사용하고자 한다면 아래와 같이 Wrapper 을 활용 해야한다.
쉽게 보자면 int는 Integer , double은 Double로 이와 같이 표기해야하며 코드는 아래와 같다.
class EmployeeInfo{
public int rank;
EmployeeInfo(int rank){
this.rank = rank;
}
}
class Person<T, S>{
public T info;
public S id;
Person(T info, S id) {
this.info = info;
this.id = id;
}
}
public class GenericDemo {
public static void main(String[] args) {
Integer id = new Integer(1);
Person<EmployeeInfo, Integer> p1 = new Person<EmployeeInfo, Integer>(new EmployeeInfo(1), id);
System.out.println(p1.id.intValue());
}
}