组合两个 Set 时出现 java.lang.UnsupportedOperationException [英] java.lang.UnsupportedOperationException when combining two Sets

查看:21
本文介绍了组合两个 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆