In the book Java Generics and Collections by Maurice Naftalin, Philip Wadler, I was going through Generics limitations and came up with doubt. May be that is answered in the book, but I think I am confused a loy.
In the following code:
List<List<?>> lists = new ArrayList<List<?>>();
lists.add(Arrays.asList(1,2,3));
lists.add(Arrays.asList("four","five"));
assert lists.toString().equals("[[1, 2, 3], [four, five]]");
As is said in the book, that nested wildcards instantiation has no problem, because for the first list , it knows that it will contain objects of list types.
But I tried to modify the above code and came up with one warning and one compile time error. I tried to do:
List<?> sample= Arrays.asList(1,2,3,4.14);
List<List<?>> lists = new ArrayList<List<?>>();
lists.add(Arrays.asList(1,2,3));
lists.get(0).add(5);
lists.add(Arrays.asList("four","five"));
System.out.println(sample.toString());
assert lists.toString().equals("[[1, 2, 3], [four, five]]");
My questions are:
1) In the first line if I write:
List<?> sample= Arrays.asList(1,2,3);
No warning is issued here but as written in the previous block, if I write:
List<?> sample= Arrays.asList(1,2,3,4.14);
a warning is issued. Why?
2) Why is there a compile time error in fourth line:
lists.get(0).add(5);
Thanks in advance.
There is a compile time exception because
lists.get(0)returns aList<?>You don’t know what is the type of this list, you know you can get elements from it (it will be at least an
Object) but you can’t put anything in it (as you’re not sure that it will fit.What would append if you wrote instead:
You have an
ArrayList<String>and you’re trying to add a number in it. So just to avoid this kind of mistake (and because the verification is done at compile time), you can’t add things if you’re not sure it will work.Regarding your warning, I don’t have any.