1

I've seen people use Map instead of HashMap to declare a HashMap.

e.g. Map mapName = new HashMap(); Whereas I'd normally use HashMap mapName = new HashMap();;

The same for a a HashSet, I've seen Set setName = new HashSet(); used, whereas I'd normally use a HashSet setName = new HashSet()

Same for ArrayList (List) and so on.

My question is, is there any benefit to doing this, or is it just a matter a perspective?

3 Answers3

6

Map is the name of the interface, which garantees a number of implemented methods.

HashMap is the name of a class that implements the aforementionned interface.

However, HashMap is not the only class to implement the Map interface. Other classes that do can be found on the Java doc Map page.

Useful links:

Java Interfaces?

What is the difference between the HashMap and Map objects in Java?

http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

Community
  • 1
  • 1
AntonH
  • 6,359
  • 2
  • 30
  • 40
  • Adding a little more information to your answer. It is important to mention that's a bad practice doing HashMap map = new HashMap();. The good practice is always having the interface at left side in the way of: Map map = new HashMap(). Many quality source tools like FindBug point this as important change. – Federico Piazza May 12 '14 at 17:36
3

As @AntonH mentioned, Map is the interface and HashMap is a concrete implementation of that interface.

To answer the final part of your question, the benefit to doing this is that it makes your code more flexible for no cost. It means that any implementation of the interface can be "plugged in" at the point where it's constructed, and the rest of the code doesn't have to change.

This applies not only to alternative implementations in the core library (HashMap vs TreeMap, for example); but to other custom implementations too (someone might write a ListeningMap which has hooks to be notified when an entry is added, for example).

If you wrote a method to accept a HashMap argument, then people could only ever pass it HashMaps. It would force callers to adopt a particular data storage, or have the overhead of casting every time they called it. And it would prevent them from doing any interesting logic (such as the aforementioned listeners, or a Map that calculates its entries dynamically).

So unless you really, specifically need for the value to be a HashMap (which is almost never the case), declaring your types as the broadest possible interface gives a lot of flexibility.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
0

Map is an interface, i.e. an abstract "thing" that defines how something can be used.

HashMap is an implementation of that interface.

enter image description here

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55