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 = new ArrayList<Integer>(data);
|
Jos
Even you can use the addAll(Collection c) method of ArrayList as well. Something like,
Java Code:
1dataCopy.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();
}
}