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);
    }



转载于:https://www.cnblogs.com/jingLongJun/p/4491038.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值