Open tonykang22 opened 1 year ago
public class Box<T> {
private T t;
public T get() {
return t;
}
public <E extends T> void set(E e) {
this.t = e;
}
}
public class BoxExample {
private static <U> void addBox(U u, List<Box<U>> boxes) {
Box<U> box = new Box<>();
box.set(u);
boxes.add(box);
}
private static <U> void outputBoxes(List<Box<U>> boxes) {
int counter = 0;
for (Box<U> box: boxes) {
U boxContents = box.get();
System.out.println("Box #" + counter + " contains [" +
boxContents.toString() + "]");
counter++;
}
}
private static void processStringList(List<String> stringList) {
}
public static void main(String[] args) {
// 명시하지 않아도 타입 추론을 하기 때문에 우항에 <> (다이아몬드 연산자)만 사용하면 된다.
ArrayList<Box<Integer>> listOfIntegerBoxes = new ArrayList<>();
// Explicit type arguments (type witness): 직접 명시해도 되지만, 타입 추론으로 인해 하지 않아도 된다.
BoxExample.<Integer>addBox(10, listOfIntegerBoxes);
BoxExample.addBox(20, listOfIntegerBoxes);
BoxExample.addBox(30, listOfIntegerBoxes);
BoxExample.outputBoxes(listOfIntegerBoxes);
// Target Type (Collections.emptyList() 생성 시, target의 type을 보고 추론해 만들어준다.)
List<String> stringlist = Collections.emptyList();
List<Integer> integerlist = Collections.emptyList();
BoxExample.processStringList(Collections.emptyList());
}
}
아이템 31. 한정적 와일드카드를 사용해 API 유연성을 높이라.
핵심 정리 1: Chooser와 Union API 개선
PECS: Producer-Extends, Consumer-Super
예시
핵심 정리 2: Comparator와 Comparable은 소비자
<? super E>
를 사용하는게 좋다.예시
더 상위 타입에서 구현 중인 경우
핵심 정리 3: 와일드카드 활용 팁
?
)로 정의한 타입에는 null을 제외한 아무것도 넣을 수 없다.?
만 단독으로 사용하는 것은 권장하지 않는다.예시