What is the difference between the HashMap and Map objects in Java?

后端 未结 13 1291
无人及你
无人及你 2020-11-22 17:07

What is the difference between the following maps I create (in another question, people answered using them seemingly interchangeably and I\'m wondering if/how they are diff

13条回答
  •  长发绾君心
    2020-11-22 17:19

    enter image description here

    Map has the following implementations:

    1. HashMap Map m = new HashMap();

    2. LinkedHashMap Map m = new LinkedHashMap();

    3. Tree Map Map m = new TreeMap();

    4. WeakHashMap Map m = new WeakHashMap();

    Suppose you have created one method (this is just pseudocode).

    public void HashMap getMap(){
       return map;
    }
    

    Suppose your project requirements change:

    1. The method should return map contents - Need to return HashMap.
    2. The method should return map key's in insertion order - Need to change return type HashMap to LinkedHashMap.
    3. The method should return map key's in sorted order - Need to change return type LinkedHashMap to TreeMap.

    If your method returns specific classes instead of something that implements the Map interface, you have to change the return type of getMap() method each time.

    But if you use the polymorphism feature of Java, and instead of returning specific classes, use the interface Map, it improves code reusability and reduces the impact of requirement changes.

提交回复
热议问题