1
以下示例取自Generics FAQ。通配符參數化不接受對象 - 爲什麼?
public class Box<T> {
private T t;
public Box(T t) {
this.t = t;
}
public void put(T t) {
this.t = t;
}
public T take() {
return t;
}
public static void main(String[] args) {
Box<?> box = new Box<Object>(new Object());
Object o = new Object();
box.put(o); // Compiler error
o = box.take(); // ok
}
}
如果你看看反編譯後的版本put()是否接受Object。那麼爲什麼編譯器不接受put()中的Object呢?
public class Box
{
public Box(Object t)
{
this.t = t;
}
public void put(Object t)
{
this.t = t;
}
public Object take()
{
return t;
}
public static void main(String args[])
{
Box box = new Box(new Object());
Object o = new Object();
o = box.take();
}
private Object t;
}