【发布时间】:2016-02-08 17:18:54
【问题描述】:
我在 java 文档和这篇文章中读到 LinkedHashMaps 的keyset() 维护秩序。
Is the order guaranteed for the return of keys and values from a LinkedHashMap object?
我的问题是,如果它保证了顺序,那么为什么LinkedHashMap 的源代码不返回一个类型为Set 的对象来保证像LinkedHashSet 这样的顺序?
我可能想到的一个原因是 LinkedHashSet 使用了一个会增加内存分配的映射(取决于 AbstractSet 的实现方式)。是否也是因为它未来证明了密钥集的实现?
就像这个答案在这篇文章中所说的那样:Is it better to use List or Collection?
返回列表符合编程到最合适的 界面。
返回 Collection 会给用户带来歧义,因为 返回的集合可以是:Set、List 或 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();
}
}
【问题讨论】:
标签: java collections linkedhashmap linkedhashset