java - 为什么 LinkedHashMap keyset() 不返回 LinkedHashSet vs Set?

标签 java collections linkedhashmap linkedhashset

我在 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 的源代码不返回类型为 SetObject 来保证像 这样的顺序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/

相关文章:

java - LinkedHashMap,方法内的功能?

java - 更改 ContentPane 的背景颜色

java - List 中的 contains() 方法未按预期工作

collections - 如何循环 Magento 集合?

collections - 使用布鲁克林主题在 Shopify 的系列页面上显示所有颜色变体

java - LinkedHashMap 中 'accessOrder' 字段的用途是什么?

android - 在 Android 上替换 JSON LinkedHashMap 对象中的转义

java - 子函数中的 RuntimeException 不应影响父调用函数 - REQUIRES_NEW 起作用吗?

java - Apache POI、Excel 2007+ XML 和 OSGI

java - 根据 Java checkstyle,方法内有太多 return 语句,如何简化代码以符合 2 返回最大值?