set调用add报错:

Map<String, String> goodsStandMap = new HashMap<>();
goodsStandMap.put("key1", "value1");
goodsStandMap.put("key2", "value2");
Set<String> unitKeySet = goodsStandMap.keySet();

报错:"exceptionTypeName":"java.lang.UnsupportedOperationException","message":null}}}
原因: map.keySet方法返回的是 keySet不是HashSet KeySet extends AbstractSet<K> implements Set<E>
keySet中没有add方法,也好理解,如果map的keyset中添加新的元素,那map中也添加key,那么value呢?
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}

final class KeySet extends AbstractSet<K> {}
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {}


posted @ 2019-07-05 11:44  为爱奋斗不息  阅读(729)  评论(0编辑  收藏  举报