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

错误信息如下:

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



  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值