"Thinking in java"의 제네릭 장을 읽었습니다. 이 프로그램은 아래에 있습니다. 아래Bruce Eckel의 "Thinking in Java"의이 제네릭 예제가 잘못 되었습니까?
public class GenericWriting {
static <T> void writeExact(List<T> list, T item) {
list.add(item);
}
static List<Apple> apples = new ArrayList<Apple>();
static List<Fruit> fruit = new ArrayList<Fruit>();
static void f1() {
writeExact(apples, new Apple());
// writeExact(fruit, new Apple()); // Error:------------------line 1
// Incompatible types: found Fruit, required Apple
}
static <T> void writeWithWildcard(List<? super T> list, T item) {
list.add(item);
}
static void f2() {
writeWithWildcard(apples, new Apple());
writeWithWildcard(fruit, new Apple());
}
public static void main(String[] args) { f1(); f2(); }
}
는 writeExact() 메소드는 정확한 매개 변수 유형 (와일드 카드)를 사용한다 "말했다. F1()에서 당신 만 List<Apple>
에 애플을 넣어이 미세 오래 작동하는지 확인할 수 있습니다. 그러나 writeExact()를 사용하면 가능해야한다고 알고 있더라도 List<Fruit>
에 Apple을 넣을 수 없습니다. "
하지만 줄 1의 주석을 제거하고 실행하면 문제가 없습니다. 아무도 나를 잘못한 곳에서 도울 수 있습니까?
을 쓰고 싶다 생각합니다. –
내가 잘못 한 것은이 책을 선택하는 것 뿐이라고 생각합니다. –
이 책의 네 번째 버전 [here] (http://www.saeedsh.com/resources/Thinking%20in%20Java%204th%20Ed.pdf)을 다운로드 할 수 있으며,이 예제는 486 페이지 (508 페이지 중)에 있습니다. PDF). 또한 제 3 판을 살펴 봤는데이 예제는 그 중 하나와 동일합니다. –