【强制】 使用 Map 的方法 keySet()/values()/entrySet()返回集合对象时,不可以对其进行添加元素操作,否则会抛出 UnsupportedOperationException 异常。

1、问题重现:

public class MapTest {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>(4);
        map.put(1, "一");
        map.put(2, "二");
        map.put(3, "三");
        Set<Map.Entry<Integer, String>> entries = map.entrySet();

        Map.Entry<Integer, String> oneEntry = getOneEntry();
        // 这里会报 java.lang.UnsupportedOperationException 异常
        entries.add(oneEntry);
    }

    public static Map.Entry<Integer, String> getOneEntry(){
        Map<Integer, String> map = new HashMap<>(1);
        map.put(4,"四");
        return map.entrySet().iterator().next();
    }
}

2、问题解析

map.entrySet()方法返回的是hashMap的内部类EntrySet
[JAVA]《JAVA开发手册》规约详解

当调用 entries.add(oneEntry);时,实际调用的是内部类EntrySet的add方法,该方法继承自父类AbstractCollection

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * <tt>UnsupportedOperationException</tt>.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IllegalStateException         {@inheritDoc}
     */
    public boolean add(E e) {
        throw new UnsupportedOperationException();
    }

 

 

 

分类:

技术点:

相关文章: