0

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.

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
Dipesh Gupta
  • 787
  • 1
  • 7
  • 20

3 Answers3

3

There is a compile time exception because lists.get(0) returns a List<?>

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:

List<List<?>> lists = new ArrayList<List<?>>();
lists.add(new ArrayList<String>());
lists.get(0).add(5);
lists.add(Arrays.asList("four","five"));

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.

Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
0

1) This line should no give a warning (and it doesn't when I try it). Which warning do you see?

2) There is a compile time error because the type of lists.get(0) is List<?>, not List<Integer. This means that the compiler has no idea whether the list is allowed to contain an integer...

Mathias Schwarz
  • 7,099
  • 23
  • 28
0

2) Why is there a compile time error in fourth line:

lists.get(0).add(5);

because you defined List> lists = new ArrayList>(); and you are trying to add simple integer 5 in List. That's why, IDE giving compilation error.

kandarp
  • 4,979
  • 11
  • 34
  • 43