gpt4 book ai didi

java - 为什么允许固定大小的数组支持的集合不实现所有接口(interface)方法?

转载 作者:行者123 更新时间:2023-12-01 07:18:19 24 4
gpt4 key购买 nike

我正在尝试执行以下操作:

Set<String> strings = map1.keySet();
strings.addAll(map2.ketSet());

在运行时,我收到 UnsupportedOperationException,似乎发生这种情况是因为 strings 是一个固定大小的数组支持集。但是如果strings是一个set,为什么它允许不实现addAll

最佳答案

因为keySet的javadoc中明确提到了(强调我的)

[...] The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

此外,如 this comment 中提到的并非所有集合都必须实现此方法。

更具体地说 - 它(集合的addAll)说,

UnsupportedOperationException - if the addAll operation is not supported by this collection

关于java - 为什么允许固定大小的数组支持的集合不实现所有接口(interface)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50218056/

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