javacollectionslinkedhashmaplinkedhashset

Why doesn't LinkedHashMap keyset() return LinkedHashSet vs Set?


I've read in java documentation and also in this post that LinkedHashMaps' keyset() maintains order. Is the order guaranteed for the return of keys and values from a LinkedHashMap object?

My question is, if it guarantees order then why doesn't the source code of LinkedHashMap return an Object of type Set that guarantees order like LinkedHashSet?

One reason I can maybe think of is that LinkedHashSet uses a map which would increase memory allocation (depending on how AbstractSet is implemented). Is it also because it future proofs implementation of keyset?

Like this answer says in this post : Is it better to use List or Collection?

Returning a List is in line with programming to the Highest Suitable Interface.

Returning a Collection would cause ambiguity to the user, as a returned collection could be either: Set, List or Queue.

So, without reading the documentation of the keyset() isn't this ambiguous?

keyset() source code:

public Set<K> keySet() {
    Set<K> ks = keySet;
    return (ks != null ? ks : (keySet = new KeySet()));
}

private final class KeySet extends AbstractSet<K> {
    public Iterator<K> iterator() {
        return newKeyIterator();
    }
    public int size() {
        return size;
    }
    public boolean contains(Object o) {
        return containsKey(o);
    }
    public boolean remove(Object o) {
        return HashMap.this.removeEntryForKey(o) != null;
    }
    public void clear() {
        HashMap.this.clear();
    }
}

Solution

  • "why doesn't the source code of LinkedHashMap return an Object of type Set that guarantees order like LinkedHashSet?"

    Because LinkedHashSet is a concrete class with it's own implementation maintaining its own data, and the keyset() method must return a view of the Map, so it cannot just copy the key data to a LinkedHashSet. See javadoc:

    Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.