• Collections.copy 报错: Source does not fit in dest


    今天在使用 Collections.copy 方法时候,报错

    Source does not fit in dest

    自己方法中的代码如下:

    List<Option> proStateList = SelectOptionsUtil.getOptionsById("prostate");
            List<Option> resultList = new ArrayList<Option>(20);// 生成新的List,防止更新操作对缓存变量影响
            Collections.copy(resultList, proStateList);//List拷贝

    首先去看Collections.copy的源码:

      int srcSize = src.size();
      if (srcSize > dest.size())
                throw new IndexOutOfBoundsException("Source does not fit in dest");

    发现是比较size的。

    而,查看ArrayList的源码,发现使用的并没有改变size。

    public ArrayList(int initialCapacity) {
            super();
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
            this.elementData = new Object[initialCapacity];
        }

    瞬间我就斯巴达了。

    借用万能的谷歌搜索,发现:http://stackoverflow.com/questions/6147650/java-lang-indexoutofboundsexception-source-does-not-fit-in-dest

    有大神遇到这个问题。

    自己查看,发现可以使用如下代码直接实现。

        List<Option> proStateList = SelectOptionsUtil.getOptionsById("prostate");
            List<Option> resultList = new ArrayList<Option>(proStateList);// 生成新的List,防止更新操作对缓存变量影响
    直接使用构造方法即可,无需使用copy方法。

        /**
         * Constructs a list containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.
         *
         * @param c the collection whose elements are to be placed into this list
         * @throws NullPointerException if the specified collection is null
         */
        public ArrayList(Collection<? extends E> c) {
            elementData = c.toArray();
            size = elementData.length;
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        }



    欢迎转载,但转载请注明原文链接[博客园: http://www.cnblogs.com/jingLongJun/]
    [CSDN博客:http://blog.csdn.net/mergades]。
    如相关博文涉及到版权问题,请联系本人。
  • 相关阅读:
    C. MP3(离散化 暴力)
    最大团、最小独立集
    欧拉函数
    In Touch(dijk+并查集优化)
    Path(2019 杭电多校第一场 ) hdu 6582(最短路模板+dinic模板)
    2019 南昌邀请赛 Winner (tarjan缩点)
    mybatis主键回填和自定义
    mybatis配置xml文件的层次结构
    Paratroopers
    Dual Core CPU
  • 原文地址:https://www.cnblogs.com/jingLongJun/p/4491038.html
Copyright © 2020-2023  润新知