我在 java 文档和这篇文章中读到了 LinkedHashMaps 的 keyset()
维护顺序。
Is the order guaranteed for the return of keys and values from a LinkedHashMap object?
我的问题是,如果它保证顺序那么为什么 LinkedHashMap
的源代码不返回一个 Set
类型的对象来保证顺序,如 LinkedHashSet
?
我可能想到的一个原因是 LinkedHashSet 使用一个会增加内存分配的映射(取决于 AbstractSet 的实现方式)。是否也是因为它 future 证明了键集的实现?
就像这个答案在这篇文章中所说: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.
所以,如果不阅读 keyset()
的文档,这不是模棱两可吗?
keyset()
源代码:
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();
}
}
最佳答案
“为什么 LinkedHashMap
的源代码不返回类型为 Set
的 Object
来保证像 这样的顺序LinkedHashSet
?"
因为 LinkedHashSet
是一个具体的类,它有自己的实现来维护自己的数据,而 keyset()
方法必须返回 Map
的 View ,因此它不能只将关键数据复制到 LinkedHashSet
。请参阅 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.
关于java - 为什么 LinkedHashMap keyset() 不返回 LinkedHashSet vs Set?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35275493/