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

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

    Adding to the top voted answer and many ones above stressing the "more generic, better", I would like to dig a little bit more.

    Map is the structure contract while HashMap is an implementation providing its own methods to deal with different real problems: how to calculate index, what is the capacity and how to increment it, how to insert, how to keep the index unique, etc.

    Let's look into the source code:

    In Map we have the method of containsKey(Object key):

    boolean containsKey(Object key);
    

    JavaDoc:

    boolean java.util.Map.containsValue(Object value)

    Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations of the Map interface.

    Parameters:value

    value whose presence in this map is to betested

    Returns:true

    if this map maps one or more keys to the specified

    valueThrows:

    ClassCastException - if the value is of an inappropriate type for this map (optional)

    NullPointerException - if the specified value is null and this map does not permit null values (optional)

    It requires its implementations to implement it, but the "how to" is at its freedom, only to ensure it returns correct.

    In HashMap:

    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }
    

    It turns out that HashMap uses hashcode to test if this map contains the key. So it has the benefit of hash algorithm.

提交回复
热议问题