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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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’sMap<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 asHashMap<String, Object>, you have to change your contract if you want to change the underlying implementation…Also
Mapis the static type of map, whileHashMapis the dynamic type of map. This means that the compiler will treat your map object as being one of typeMap, 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
Mapinstead of the stricter (because less abstract)HashMaptype. That way, the consumer of your API can be flexible about what kind ofMapimplementation they want to pass to your method..