在ITeye上看到一个问题
问题原帖地址:http://www.iteye.com/topic/164966
《Java 编程思想》15.10.2 逆变例子如下: (393页)
public class Fruit {}
public class Apple extends Fruit {}
//: generics/GenericWriting.java
import java.util.*;
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:
// 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(); }
} ///:~
//=================================
红色部分按书上说明应该编译出错,可是我试了一下,可以通过编译,不知是什么问题。
iteye某人的回答真是。。。
后来鄙人上SOF上搜寻答案,发现还真有
答案原帖地址:
However, writeExact( )
does not allow you to put an Apple
into aList<Fruit>
, even though you know that should be possible.
This is incorrect. writeExact
can put an Apple
in to aList<Fruit>
. <T>
is inferred to be Fruit
andApple
(presumably) is a subtype of Fruit
.
You should check the Java version that your book is written for. It may be that in an older version of Java this would not compile due to less inference on the part of the compiler. Otherwise the book contains an error.
This will compile as of Java 6+ that I can confirm.
感觉是Java版本的问题,毕竟作者用的Java SE5.我用的是Java 7.