java - Why doesn't LinkedHashMap keyset() return LinkedHashSet vs Set? -
i've read in java documentation , in post linkedhashmaps' keyset() maintains order. is order guaranteed return of keys , values linkedhashmap object?
my question is, if guarantees order why doesn't source code of linkedhashmap return object of type set guarantees order linkedhashset?
one reason can maybe think of linkedhashset uses map increase memory allocation (depending on how abstractset implemented). because future proofs implementation of keyset?
like answer says in post : is better use list or collection?
returning list in line programming highest suitable interface.
returning collection cause ambiguity user, returned collection either: set, list or queue.
so, without reading documentation of keyset() isn't 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(); } }
"why doesn't source code of linkedhashmap return object of type set guarantees order linkedhashset?"
because linkedhashset concrete class it's own implementation maintaining own data, , keyset() method must return view of map, cannot copy key data linkedhashset. see javadoc:
returns
setview of keys contained in map. set backed map, changes map reflected in set, , vice-versa.
Comments
Post a Comment