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

后端 未结 13 1168
无人及你
无人及你 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:24

    HashMap map1 = new HashMap();
    Map map2 = new HashMap();  
    

    First of all Map is an interface it has different implementation like - HashMap, TreeHashMap, LinkedHashMap etc. Interface works like a super class for the implementing class. So according to OOP's rule any concrete class that implements Map is a Map also. That means we can assign/put any HashMap type variable to a Map type variable without any type of casting.

    In this case we can assign map1 to map2 without any casting or any losing of data -

    map2 = map1
    

提交回复
热议问题