5

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){

}
1
  • The answer to your second question is yes for the reason you stated. The answer to your first question is yes because it enforces the correct behaviour in your second question (you can't write methods which accept HashMap then try to pass a Map, the compiler won't let you.) Commented Dec 27, 2013 at 2:11

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

5

The second version is preferred because if you want to write code later to change map to a different kind of Map, you will need to use the second version. But it really is a matter of personal preference.

Comments

0

in the perspective of the object-oriented,During compilation, the method is bound reference class type, so HashMap map = new HashMap(); You can us hashMap methods ,Including the realization map and extended. But , Map map = new HashMap(); You can only use methods declared in map .Can not used hashMap methods.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.