java集合複製的另一種方法__java

來源:互聯網
上載者:User

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.