gpt4 book ai didi

java - 为什么抽象实现由 Map.values() 返回?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:52:36 24 4
gpt4 key购买 nike

Map<Integer, String> map = new TreeMap<>();
map.put(1, "String1");
map.put(2, "String2");
map.put(3, "String3");

我想将 map 的值转换为 set。我知道我可以轻松做到

Set<String> set = new HashSet<>(map.values());

在考虑这个问题时,我很好奇 map.values() 本身到底是什么?所以我试了一下

System.out.println("Set:"+ (map.values() instanceof Set));      
System.out.println("List:"+ (map.values() instanceof List));
System.out.println("Queue:"+ (map.values() instanceof Queue));
System.out.println("SortedSet:"+ (map.values() instanceof SortedSet));

结果出乎意料的是

Set:false
List:false
Queue:false
SortedSet:false

This是所有文档所说的。

a collection view of the values contained in this map

然后我查看了反编译的类文件。

public Collection<V> values() {
if (values == null) {
values = new AbstractCollection<V>() {
public Iterator<V> iterator() {
return new Iterator<V>() {
private Iterator<Entry<K,V>> i = entrySet().iterator();

public boolean hasNext() {
return i.hasNext();
}

public V next() {
return i.next().getValue();
}

public void remove() {
i.remove();
}
};
}

public int size() {
return AbstractMap.this.size();
}

public boolean isEmpty() {
return AbstractMap.this.isEmpty();
}

public void clear() {
AbstractMap.this.clear();
}

public boolean contains(Object v) {
return AbstractMap.this.containsValue(v);
}
};
}
return values;
}

为什么java返回一个抽象实现而不是List/Set/Queue可以立即兼容用例?

最佳答案

我不知道您使用的是哪个 Java 版本,但我没有看到 values() 返回的抽象类实例。它返回 TreeMap.Values 的实例,这是一个扩展 AbstractCollection 的类。

至于为什么它不返回 Set - 这仅仅是因为值的集合可能包含重复项,这是 Set 不允许的.

List 也不理想,因为它暗示值是有序的,这对于所有 Map 实现(例如 HashMap).

顺便说一句,您可以简单地打印map.value().getClass().getName(),而不是像打印map.values() instanceof Set 这样的东西查看实际的实现类。

关于java - 为什么抽象实现由 Map.values() 返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56666505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com