zoukankan      html  css  js  c++  java
  • 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]。
    如相关博文涉及到版权问题,请联系本人。
  • 相关阅读:
    Java第四章课后整理
    java第三章课后作业1
    Java第三章整理
    JAVA第二章课后作业
    JAVA第二章整理
    java课后作业1
    JAVA第一章整理实验
    JAVA大道至简第一章伪代码
    文本数据特征选取的四种方法
    时域分析与频率分析的比较
  • 原文地址:https://www.cnblogs.com/jingLongJun/p/4491038.html
Copyright © 2011-2022 走看看