现在的位置: 首页 > 综合 > 正文

[Java错误]使用Collections中的copy方法复制ArrayList产生的错误

2018年02月15日 ⁄ 综合 ⁄ 共 1830字 ⁄ 字号 评论关闭

错误信息如下:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest
at java.util.Collections.copy(Unknown Source)

错误源代码:

import java.util.ArrayList;
import java.util.Collections;

public class test_4 {
	public static void main(String args[]) {
		ArrayList<Integer> List = new ArrayList<Integer>();
		for (int i = 0; i < 10; i++)
			List.add(i); 
		ArrayList<Integer> newList = new ArrayList<Integer>(100);
		Collections.copy(newList, List);
		System.out.println(List.toString());
		System.out.println(List);
		System.out.println(newList);
		List.set(2, 8);
		System.out.println(newList);
	}
}

看下API文档中对于copy方法的介绍如下:

public static <T> void copy(List<? super T> dest,
                            List<? extends T> src)
Copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is
longer, the remaining elements in the destination list are unaffected.

This method runs in linear time.

Type Parameters:
T - the class of the objects in the lists
Parameters:
dest - The destination list.
src - The source list.
Throws:
IndexOutOfBoundsException -
if the destination list is too small to contain the entire source List.
UnsupportedOperationException -
if the destination list's list-iterator does not support the set operation.
错误的方式打印出来的newList.size()==0!!!可是我们明明将其设置为了100!Why?通过仔细观察,发现100并不是指的是newList的size,而是其容量(打个比方,你有一个桶,它的容量很大,但是它是空的!!!)。笔者认识到该错误后,对源码进行了修改,得到了正确的方式,修改如下:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class test_4 {
	public static void main(String args[]) {
		ArrayList<Integer> List = new ArrayList<Integer>();
		for (int i = 0; i < 10; i++)
			List.add(i); 
		ArrayList<Integer> newList = new ArrayList<Integer>(Arrays.asList(new Integer[List.size()]));
		Collections.copy(newList, List);
		System.out.println(List.toString());
		System.out.println(List);
		System.out.println(newList);
		List.set(2, 8);
		System.out.println(newList);
	}
}

抱歉!评论已关闭.