-2

What are the difference? Please see below.

HashMap<Integer, String> hashMap = new HashMap<Integer, String>();

and

Map<Integer, String> hashMap = new HashMap<Integer, String();

Are they interchangeable ?

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525

3 Answers3

5

A Map<K, V> is an interface, a HashMap<K, V> is a class implementing the interface.

I always prefer the second option, unless you specifically want the charasterics of a HashMap<K, V>.

With the latter approach it is possible to switch out the HashMap<K, V> for another implementation of the Map<K, V> easily.

Another example of coding against interfaces

Take the List<E> vs ArrayList<E> approach as other example:

  • If you define it as ArrayList<E> list = new ArrayList<>(), then you cannot easily change it to a LinkedList<>(), as ArrayList<E> list = new LinkedList<>() does not compile.
  • However if you declare it as List<E> list = new ArrayList<>(), then you can switch it out to a LinkedList<>() at any time.

An example of coding against interfaces in methods

Let's say you have a method that accepts a List<E>, what should you do then?

  1. Make it as void method(ArrayList<E> list);
  2. Or make it as void method(List<E> list)

Now you generally always want it to be a List<E>, when you do not care about the type of the list, and you only care about the operations available in the List<E> interface.

However there are cases where you possibly do want to force constant access times, it that case it could very well make sense to only let your method accept ArrayList<E>, because that implementation provided constant access times.

Community
  • 1
  • 1
skiwi
  • 66,971
  • 31
  • 131
  • 216
0

The difference is in the variable hashMap. If you create it like this:

HashMap hashMap = new HashMap();

you will be able to use all of HashMap's methods.

If you create it like this:

Map hashMap = new HashMap();

then you will be restricted to the methods of the Map interface.

The difference is that HashMap is an implementation of the Map interface. You can say that in most cases it is better to use the Map interface because generally you don't need to know about the details of the implementation and this way you can swap implementations in no time.

This comes from the general guideline of program to interfaces not implementations.

Just a note:

You should use generics where applicable.

Community
  • 1
  • 1
Adam Arold
  • 29,285
  • 22
  • 112
  • 207
0

As far as i see from the javadoc, HashMap does not add any new methods, so for these two classes there is no difference.

On general principle, it's better to use interfaces rather than classes whenever possible.