zoukankan      html  css  js  c++  java
  • [JAVA]《JAVA开发手册》规约详解

    【强制】 使用 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

    当调用 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();
        }
     
  • 相关阅读:
    第一个TS文件
    盒子模型
    不稳定的排序算法
    状态码Status Code
    从输入URL到页面加载完成发生了什么?
    JavaScript中var、let、const的区别
    explain 详解 (转)
    HttpServletRequest对象方法的用法 (转)
    数据一致性理解
    logback 使用详解 (转)
  • 原文地址:https://www.cnblogs.com/zhengxl5566/p/11106226.html
Copyright © 2011-2022 走看看