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 ?
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 ?
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.
Take the List<E>
vs ArrayList<E>
approach as other example:
ArrayList<E> list = new ArrayList<>()
, then you cannot easily change it to a LinkedList<>()
, as ArrayList<E> list = new LinkedList<>()
does not compile.List<E> list = new ArrayList<>()
, then you can switch it out to a LinkedList<>()
at any time.Let's say you have a method that accepts a List<E>
, what should you do then?
void method(ArrayList<E> list)
;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.
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.
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.