今天在使用 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拷贝
int srcSize = src.size(); if (srcSize > dest.size()) throw new IndexOutOfBoundsException("Source does not fit in dest");
而,查看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); }