What is the benefit of polymorphism using Collection interface to create ArrayList object?

If you declare myList as ArrayList, you fix its concrete type. Everyone using it will depend on this concrete type, and it is easy to (even inadvertently) call methods which are specific to ArrayList. If sometime later you decide to change it to e.g. LinkedList or CopyOnWriteArrayList, you need to recompile – and possibly even change – client code. Programming for interfaces eliminates this risk.

Note that between Collection and ArrayList, there is another level of abstraction: the List interface. Typically the usage pattern of a list is very different from that of a map, set or queue. So the type of collection you need for a job is usually decided early on, and is not going to change. Declaring your variable as a List makes this decision clear, and gives its clients useful information regarding the contract this collection obeys. Collection OTOH is usually not very useful for more than iterating through its elements.

Leave a Comment