I'm learning Java Generics recently, and just trying to go though "Java Generics FAQ".
Below question (#304) regarding wildcard parameterized type kinda confused me, would appreciate your help.
Code Example:
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 boolean equalTo(Box<T> other) { return this.t.equals(other.t); }
public Box<T> copy() { return new Box<T>(t); }
}
class Test {
public static void main(String[] args) {
Box<?> box = new Box<String>("abc");
box.put("xyz"); // error
box.put(null); // ok
String s = box.take(); // error
Object o = box.take(); // ok
boolean equal = box.equalTo(box); // error {confused}
equal = box.equalTo(new Box<String>("abc")); // error {confused}
Box<?> box1 = box.copy(); // ok
Box<String> box2 = box.copy(); // error
}
}
Can not figure out why below two method called will fail:
boolean equal = box.equalTo(box);
equal = box.equalTo(new Box<String>("abc"));
Thanks