Chapter 13 제네릭
결정되지 않은 타입을 파라미터로 처리하고 실제 사용할 때 파라미터를 구체적인 타입으로 대체시키는 기능이다.
public class Box<T> {
public T content;
}
Box<String> box = new Box<String>();
box.content = "안녕하세요";
String content = box.content; // 강제 타입 변환 없이 값을 바로 얻을 수 있음
Box<Integer> box = new Box<Integer>();
box.content = 100;
int content = box.content; // 강제 타입 변환 없이 값을 바로 얻을 수 있음
특정 타입과 자식 또는 구현 관계에 있는 타입만 대체할 수 있는 타입 파라미터이다.
public class GenericExample {
public static <T extends Number> boolean compare(T t1, T t2) {
System.out.println("compare(" + t1.getClass().getSimpleName() + ", "
+ t2.getClass().getSimpleName() + ")");
double v1 = t1.doubleValue();
double v2 = t2.doubleValue();
return (v1 == v2);
}
public static void main(String[] args) {
boolean result1 = compare(10, 20); // Integer 타입으로 대체
System.out.println(result1);
System.out.println();
boolean result2 = compare(4.5, 4.5); // Double 타입으로 대체
System.out.println(result2);
}
}
범위에 따라 대체될 수 있는 타입을 다르게 설정할 수 있다.
// Student 와 자식 클래스만 가능
<? extends Student>
// Worker 와 부모 클래스만 가능
<? super Worker>
// 모든 타입 가능
<?>