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