Mohammad Karmi :
I have the following code working and I'm not sure why it doesn't throw an exception:
List[] x=new ArrayList[2];
x[0]=new ArrayList<Integer>();
x[1]=new ArrayList<String>();
x[0].add("test");
x[1].add(5);
System.out.println(x[0]);
System.out.println(x[1]);
This prints:
[test]
[5]
x[0]
is array of integer and it add String without any issue. x[1]
is array of String and it add integer without any issue.
How does that work?
Samuel Philipp :
You have declared an array of raw typed lists. Generic values do not exist at runtime, after you have compiled your code. So basically your lists are of type List<Object>
.
"test"
is aString
, which is basically anObject
5
gets autoboxed to anInteger
which is also anObject
So your compiler will not throw any error. If you are using an IDE it might be warn you:
Unchecked call to 'add(E)' as a member of raw type `java.util.List'
(From IntelliJ)