Possible Duplicate:
Java - HashMap vs Map objects
What's the difference between :
Map <String,Integer>myMap = new HashMap<String,Integer>();
VS
HashMap <String,Integer> map = new HashMap<String,Integer>();
Regards,Ron
Possible Duplicate:
Java - HashMap vs Map objects
What's the difference between :
Map <String,Integer>myMap = new HashMap<String,Integer>();
VS
HashMap <String,Integer> map = new HashMap<String,Integer>();
Regards,Ron
There is no difference between the objects. There is a difference in the interface you have to the object. In the first case, the interface is HashMap<String, Object>
, whereas in the second it's Map<String, Object>
. The underlying object, though, is the same.
The advantage to using Map<String, Object>
is that you can change the underlying object to be a different kind of map without breaking your contract with any code that's using it. If you declare it as HashMap<String, Object>
, you have to change your contract if you want to change the underlying implementation...
Also Map
is the static type of map, while HashMap
is the dynamic type of map. This means that the compiler will treat your map object as being one of type Map
, even though at runtime, it may point to any subtype of it...
This practice of programming against interfaces instead of implementations has the added benefit of remaining flexible: You can for instance replace the dynamic type of map at runtime, as long as it is a subtype of Map
(e.g. LinkedHashMap
), and change the map's behavior on the fly.
A good rule of thumb is to remain as abstract as possible on the API level: If for instance a method you are programming must work on maps, then it's sufficient to declare a parameter as Map
instead of the stricter (because less abstract) HashMap
type. That way, the consumer of your API can be flexible about what kind of Map
implementation they want to pass to your method..
Difference is:
when you use Map
as a type you can switch implemenation (HashMap) to other!
its a good thing!
EDIT: read this - What does it mean to "program to an interface"?
One additional point.
Declaring the variable as a Map prevents you from using the clone() method provided by the HashMap class.
so, if you use:
Map <String,Integer>myMap = new HashMap<String,Integer>();
then you can't use:
Map<String,Integer> myMap2 = myMap.clone();
Other than that, they're pretty interchangeable.