0

My initial question was:
Why does the second creation fail?
This question was marked as already answered with the hint to change the question so it's something new. I will do so now

List<Animal> list = new ArrayList<Animal>();
List<Animal> list2 = new ArrayList<Cat>();

I understand that now. It is because later on you would use list2 as List of Animals. As soon as you would add a Dog, we would have a ClassCastException or similar. This is a situation that should be eliminated by using generics and thus is unacceptable else the generics implementation would be useless.

As in one of the comments is stated this should work:

List<? extends Animal> list3 = new ArrayList<Cat>();

Then why suddenly is the above explained problem gone?

JPT
  • 410
  • 2
  • 7
  • 18
  • In short `List list2` would allow you to add *any* object, for instance Integer, Boolean, Cat, but `new ArrayList()` allows only Strings (or it subtypes if they could exist). – Pshemo Feb 03 '19 at 09:41
  • TL;DR: a `List` isn't a `List` because you can add an `Object` to the latter but not the former. – Andy Turner Feb 03 '19 at 09:41
  • Ahhh. now I understand. The receiving code would believe the List accepts everything and so break as soon as it does not add a String. We would produce a situation which we wanted to eliminate through generics. – JPT Feb 03 '19 at 09:43
  • @JPT but you could declare `List extends Object> list2` (or, equivalently, `List> list2`), since the compiler would then prevent you adding anything except literal `null` to that list. – Andy Turner Feb 03 '19 at 09:53

0 Answers0