调用Set.add(All)出现java.lang.UnsupportedOperationException异常原因以及解决方法

一个初学者很常见的错误,因为困扰了我有一些时间,所以就写在这里备忘并希望帮助其他初学java的人。

首先看一段代码:

    Map<String, Integer> map = new HashMap<>();
    map.put("a", 0);
    map.put("b", 1);
    map.put("c", 2);
		 
    Set<String> set = map.keySet();
    set.add("w");

  或者把set操作改成这个样子:

    Set<String> set = map.keySet();		 
    Set<String> tmp = new HashSet<>();
    tmp.add("w");
    set.addAll(tmp);

 这两段代码看起来没什么问题,不过实际运行会出现一个异常:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractCollection.add(Unknown Source)
	at java.util.AbstractCollection.addAll(Unknown Source)



Map.keySet理论上来讲是返回一个Set集合,那么向里面添加一个元素为什么会报错呢?原因其实很简单,不过初学者真心想不到,我们先看一下Map.keySet的帮助文档:

Set<String> java.util.Map.keySet()

keySet
Set<K> keySet()

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.
Returns:a set view of the keys contained in this map

注意说明的最后一句话“ 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.”可见Map.keySet返回的Set对象仅仅支持元素的移除,并不支持增改!所以当增加元素时才会爆出这个异常。



解决方法:

其实也比较简单,我们利用构造函数将Map.keySet返回的集合拷贝一份就好了:

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



猜你喜欢

转载自blog.csdn.net/qq_37549266/article/details/79718820