We have the following code:
public class TestGenerics {
static <T> void mix(ArrayList<T> list, T t) {
System.out.println(t.getClass().getName());
T item = list.get(0);
t = item;
System.out.println(t.getClass().getName());
}
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<Object>();
list.add(new Integer(3));
mix(list, "hello world");
}
}
At the output, I get:
java.lang.String
java.lang.Integer
This is nonsense - we just assigned Integerto Stringwithout receiving ClassCastException! We cannot write like this:
String s = new Integer(3);
but this is what we just did here.
Is this a mistake or something else?
source
share