java.lang.UnsupportedOperationException when combining two Sets(组合两个 Set 时出现 java.lang.UnsupportedOperationException)
问题描述
我有 2 个不同的 HashMap 实例
I have 2 different instances of HashMap
我想合并两个 HashMap 的键集;
I want to merge the keysets of both HashMaps;
代码:
Set<String> mySet = hashMap1.keySet();
mySet.addAll(hashMap2.keySet());
例外:
java.lang.UnsupportedOperationException
at java.util.AbstractCollection.add(AbstractCollection.java:238)
at java.util.AbstractCollection.addAll(AbstractCollection.java:322)
我没有收到编译警告或错误.
I don't get a compile warning or error.
从 java doc 这应该可以工作.即使添加的集合也是一个集合:
From java doc this should work. Even if the added collection is also a set:
boolean addAll(Collection c)
将指定集合中的所有元素添加到此集合中,如果它们不存在(可选操作).如果指定collection 也是一个集合,addAll 操作有效地修改了这个集合使得它的值是两个集合的并集.行为如果指定的集合被修改,则此操作的未定义操作进行中.
Adds all of the elements in the specified collection to this set if they're not already present (optional operation). If the specified collection is also a set, the addAll operation effectively modifies this set so that its value is the union of the two sets. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress.
推荐答案
如果你查看 HashMap#keySet()
方法,你会得到你的答案(强调我的).
If you look at the docs of the HashMap#keySet()
method, you'll get your answer(emphasis mine).
返回此映射中包含的键的 Set 视图.套装是由地图支持,因此对地图的更改会反映在集合中,并且反之亦然.如果在对集合进行迭代时修改了地图进行中(通过迭代器自己的删除操作除外),迭代的结果是不确定的.集合支持元素移除,从地图中移除对应的映射,通过Iterator.remove、Set.remove、removeAll、retainAll 和 clear操作.不支持 add 或 addAll 操作.
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. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. 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.
因此,您需要创建一个新集合并将所有元素添加到其中,而不是将元素添加到 keySet()
返回的 Set
中.
Therefore, you need to create a new set and add all the elements to it, instead of adding the elements to the Set
returned by the keySet()
.
这篇关于组合两个 Set 时出现 java.lang.UnsupportedOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:组合两个 Set 时出现 java.lang.UnsupportedOperationException
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01