Let us 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");
}
}
In the output I get:
java.lang.String
java.lang.Integer
It's nonsense - we've just assigned Integer
to String
without getting ClassCastException
! We can't write it like that:
String s = new Integer(3);
but this is what we have just done here.
Is it a bug or something?