Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using Map and HashMap as declared type [duplicate]

Tags:

java

hashmap

map

What's the difference between the following two declaration statements:

HashMap<Character, Character> map = new HashMap<Character, Character>();

Map<Character, Character> map = new HashMap<Character, Character>();

Any advantages of using the interface Map instead of HashMap in this particular case?

In the following case, is Map definitely better because the method can accept different types of maps?(if it is intended to)

public void method(Map map){

}
like image 594
Ryan Avatar asked Dec 27 '13 01:12

Ryan


1 Answers

There is no underlying difference. It is more about the interface. There's an advantage of using a Map though, that is you can change the object to be a different kind of a Map without breaking the contract of the code using it.

The HashMap is an implementation of Map, which is part of the Java Collections Framework. If you settle on using the HashMap and then the other party wishes for something different, like LinkedHashMap (preserves iteration order), then you have to change things around. Here's a diagram (courtesy ProgramCreek).

enter image description here

There are other things like computational time complexity, if you care about performance. Here's a small table that helps. Choosing the right thing is a question of design and need i.e. what are you trying to do. It varies from project to project.

enter image description here

like image 193
Ali Gajani Avatar answered Oct 09 '22 08:10

Ali Gajani