Any simple way to explain why I cannot do List animals = new ArrayList()? [duplicate]

Imagine you create a list of Dogs. You then declare this as List<Animal> and hand it to a colleague. He, not unreasonably, believes he can put a Cat in it.

He then gives it back to you, and you now have a list of Dogs, with a Cat in the middle of it. Chaos ensues.

It’s important to note that this restriction is there due to the mutability of the list. In Scala (for example), you can declare that a list of Dogs is a list of Animals. That’s because Scala lists are (by default) immutable, and so adding a Cat to a list of Dogs would give you a new list of Animals.

Leave a Comment