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.