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

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

    In your second example the "map" reference is of type Map, which is an interface implemented by HashMap (and other types of Map). This interface is a contract saying that the object maps keys to values and supports various operations (e.g. put, get). It says nothing about the implementation of the Map (in this case a HashMap).

    The second approach is generally preferred as you typically wouldn't want to expose the specific map implementation to methods using the Map or via an API definition.

    0 讨论(0)
提交回复
热议问题