Demystifying the Distinction between HashMap and Map Objects
In Java, the HashMap and Map objects often appear interchangeable, prompting confusion regarding their underlying differences. To clarify, there is no difference in the objects themselves—in both cases, you obtain a HashMap with a String key and Object value.
The distinction lies in the interface you associate with the object. When you declare the object as HashMap
Let's explore a practical example to illustrate this concept:
Consider a class named Foo that initializes two internal maps, things and moreThings, and shares them through accessor methods. These maps are initially implemented as HashMaps.
Now, suppose a subclass of Foo, SpecialFoo, utilizes a common method to manipulate both things and moreThings. This method is defined with the same interface as the accessor methods (HashMap
Later on, if you decide to replace the HashMap implementation in Foo with TreeMap, SpecialFoo will encounter a compilation error because the contract has been violated—Foo is now providing TreeMaps instead of HashMaps. This necessitates a revision of SpecialFoo.
To avoid such a situation, it's prudent to declare the accessor methods and internal maps using the general interface, Map
Coding to the most general interface is generally less brittle and more adaptable. By adhering to this principle, you maintain flexibility and prevent unforeseen errors when implementing changes to your codebase.
The above is the detailed content of HashMap vs. Map: When Should You Use Which?. For more information, please follow other related articles on the PHP Chinese website!