0

This is kinda working:

    ArrayList<Object> list1 = new ArrayList<>();
    list1.add("Hello");
    list1.add(1.5);
    list1.add(new Whatever());
    ArrayList<ArrayList<Object>> listAll = new ArrayList<>();
    listAll.add(list1);

In an ArrayList of Object you can add any Object... also you can add the same ArrayList with Objects into another ArrayList of Object. Why is this not working:

    ArrayList<String> list1 = new ArrayList<>();
    list1.add("Hello");
    list1.add(new String("World!"));
    ArrayList<ArrayList<Object>> listAll = new ArrayList<>();
    listAll.add(list1);

I have an ArrayList of Strings (String is an Object) and I cannot add these although these are Objects in listAll.

PS: JDK1.7

Edit: Well I do read this 'duplicate', about Dogs and Cats. Not sure I got it, but alright :)

silla
  • 1,257
  • 4
  • 15
  • 32
  • Because generics type are invariant. `List` is not a subtype of `List`. – Alexis C. Jan 28 '14 at 11:01
  • 1
    @silla in your first example, `ArrayList` is an `ArrayLst` (obviously) but in your second example `ArrayList` is not an `ArrayList`. – assylias Jan 28 '14 at 11:15

1 Answers1

0

Everything here is an instance of Object but reverse isn't true.

(String is an Object but Object is not String)

That is the reason ArrayList of type string will not accept Object but only String.

Amit Sharma
  • 1,202
  • 11
  • 26
  • You are wrong: in the example above, an ArrayList should be added to an ArrayList>. The real reason is referred to in the comment of assylias – mschenk74 Jan 28 '14 at 11:04