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();
        }
     
  • 相关阅读:
    datepicker防手动输入
    [ACM]Link-Cut Tree实现动态树初探
    STL priority_queue 优先队列 小记
    hihoCoder挑战赛1 毁灭者问题
    python编程技巧
    openstack horizon 学习(3) DataTable
    Upcasting, downcasting in JAVA
    SGU 145
    URAL 1003,1004
    自建物流的无人机实验(困难)
  • 原文地址:https://www.cnblogs.com/zhengxl5566/p/11106226.html
Copyright © 2011-2022 走看看