我们经常使用 HashMap 集合的 KeySet 来获取所有的 key ,当认为它就是和 HashSet 之类的时候;那你就打错特错了!!!
这其实就和 Arrays.asList 方法类似的
错误使用


Set<String> keys = map.keySet();
keys.addAll(oldKeysList);

这个时候就会报错了
查看源码之后 keySet() 获取的是 HashMap 中的一个内部类 KeySet ; 可以看出这个内部类并没有实现 addAll 之类的方法,也就是不具备 Set 接口的一些方法;因此用的时候需要注意

    final class KeySet extends AbstractSet<K> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<K> iterator()     { return new KeyIterator(); }
        public final boolean contains(Object o) { return containsKey(o); }
        public final boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }
        public final Spliterator<K> spliterator() {
            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }