1

I have surprisingly never understood the purpose of doing this:

Map telephoneNumbers = new HashMap();
List<Object> list = new ArrayList<Object>();

instead of doing this:

HashMap telephoneNumbers = new HashMap();
ArrayList<Object> list = new ArrayList<Object>();

?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

3 Answers3

2

The first two sentences abstract the implementation of your collections. I mean, you know you have a Map and a List but you are not chained to an specific implementation.

On the other hand, variables telephoneNumbers and list are forced to use the concrete implementation: a HashTable and a List in an array.

So if you use your first variable set you are programming to an interface and not to implementation which is a basic OOP principle: What does it mean to "program to an interface"?

Community
  • 1
  • 1
2

When you do:

HashMap telephoneNumbers = new HashMap();
ArrayList<Object> list = new ArrayList<Object>();

You are tied to a specific implementation, i.e. ArrayList. If you were to pass the list object further to other methods, then you are not much flexible. If you program to interface, say Collection instead (which is extended by List), you can change the implementation later. For example, if the objects in the list should be unique, then you could easily change it to be a Set instead (because sets only contain unique objects):

HashMap telephoneNumbers = new HashMap();
Collection<Object> list = new HashSet<Object>(); 

The principle of programming to an interface is really about dependency relationships. It is closely related to the concept of OO concept of Encapsulation:

  • A language mechanism for restricting access to some of the object's components.
  • A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

The most important aspect is that by following programming-to-an-interface paradigm we are asking ourself "what" the class can do but not "how" it will do it, which is concerned with the actual implementation.

Using ArrayList you are tightly coupling your code to the ArrayList class. If you only use the generic methods that are in the Collection interface (add(), remove() etc) then it definitely makes sense to declare your list as an interface of type Collection.

  • [An example](http://stackoverflow.com/a/22373138/1122039) of the advantage of interfaces - it would not be so easy if JsonObjectBuilder was a class. – Cebence Mar 14 '14 at 08:23
1

One reason -- it makes it easier to swap out implementations.

Suppose you want to use a TreeMap instead of HashMap, so you can print the telephone numbers in order. Or maybe you want to use a LinkedList instead of ArrayList so you can insert/delete/sort more quickly.

If you use the interface version (Map and List), then you would only have to make these changes in one place, where you constructed the data structures.