Java array of lists working when type of list is different

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 a String, which is basically an Object
  • 5 gets autoboxed to an Integer which is also an Object

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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=122473&siteId=1