java集合复制的另一种方法

Question:

Hi,

I want to copy a List<Integer> to an ArrayList<Integer> but I can't seem to be able to do so...I don't want to cast it...Below is my code...Please help


List<Integer> data = some data;
ArrayList<Integer> dataCopy = new ArrayList<Integer>();
Collections.copy(dataCopy, data);


I keep getting the following exception: 

Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest


Answer:


Let an ArrayList constructor do the job:

Java Code:
1
ArrayList<Integer> dataCopy = newArrayList<Integer>(data);
kind regards,

Jos


Even you can use the addAll(Collection c) method of ArrayList as well. Something like,
Java Code:
1
dataCopy.addAll(data);

Goldest



My code below:


import java.util.*;

public class Algorithms1 {
	private Character[] ch = {'P', 'C', 'M'};
//	private Character[] chn = new Character[3];
	private List <Character>list ;
	private List <Character>copyOfList ;
	
	public Algorithms1()
	{
		
		list =  Arrays.asList(ch);
	//	copyOfList = Arrays.asList(chn);
		
		System.out.println("Initial List:");
		print(list);
		
		Collections.reverse(list);
		System.out.println("After calling reverse:");
		print(list);
		
		
		/**
		 * 使用Collections.copy(copyOfList, list);的话会出现类型能干不匹配的异常
		 * 那么我们复制数组也可以使用ArrayList的构造函数来实现
		 * 当然非要使用copy方法 那么使用单行注释的内容也可
		 * 这个例子主要说明复制不要拘泥于copy方法
		 * 有时候用构造函数,有时候addall也成
		 */
		
		//Collections.copy(copyOfList, list);
		copyOfList = new ArrayList(list);
		System.out.println("After copying");
		print(copyOfList);
		
		Collections.fill(list, 'R');
		System.out.println("After calling fill:");
		print(list);
		
		
		
	}
	
	public void print (List<Character> listRef)
	{
		System.out.print("The list is: ");
		for (Character list: listRef)
		{
			System.out.printf("%s ", list);
		}
		System.out.println();
		
		compare(listRef);
		System.out.println();
	}
	
	public void compare (List<Character> listRef)
	{
		System.out.printf("Max: %s,  Min: %s\n", Collections.max(listRef),
				Collections.min(listRef));
	}
	public static void main(String[] argc)
	{
		new Algorithms1();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值