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){
}
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With