Why doesn't new Map methods generate entry accesses on LinkedHashMap?

342 Views Asked by At

Javadocs of LinkedHashMap in JDK8:

Invoking the put or get method results in an access to the corresponding entry (assuming it exists after the invocation completes). The putAll method generates one entry access for each mapping in the specified map, in the order that key-value mappings are provided by the specified map's entry set iterator. No other methods generate entry accesses.

Why doesn't new Map methods generate entry accesses on LinkedHashMap? Especially getOrDefault(). Doesn't this violate principle of least astonishment?

@PeterLawrey it is clear from the source code:

getOrDefault is overriden in HashMap:

public V getOrDefault(Object key, V defaultValue) {
     Node<K,V> e;
     return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}

LinkedHashMap extends HashMap and overrides only get():

public V get(Object key) {
    Node<K,V> e;
    if ((e = getNode(hash(key), key)) == null)
        return null;
    // generating entry access -- comment by me
    if (accessOrder)
        afterNodeAccess(e);
    return e.value;
}

Thus, entry access is not generated by getOrDefault().

0

There are 0 best solutions below