JAVA數組與List相互轉換

來源:互聯網
上載者:User

標籤:工具類   一起   highlight   arrays   operation   its   結果   list   注意   

1.數組轉成List

數組轉成List可以用方法 :Arrays.asList,一起來瞭解一下

 System.out.println(Arrays.asList(new String[] { "a", "b" }));

列印:[a, b]

List<Integer> asList2 = Arrays.asList(new Integer[] { 1, 2 });System.out.println(asList2);

列印:[1, 2]

以下會得到非預期的結果

List<int[]> asList = Arrays.asList(new int[] { 1, 2 });System.out.println(asList); 

列印:[[[email protected]]

 如果你打算將一個基本類型的數群組轉換為所對應的封裝類型的list,使用Apache Commons Lang吧,可能你的項目正在使用它,類似下面這樣使用ArrayUtils.toObject:

List<Integer> list = Arrays.asList(ArrayUtils.toObject(new int[] { 1, 2 }));System.out.println(list);

列印:[1, 2]

 

注意使用工具類Arrays.asList()把數組轉成集合時,不能使用其修改集合的相關方法,它的add/remove/clear方法會拋出java.lang.UnsupportedOperationException異常。asList的返回對象是一個Arrays內部類,並沒有實現集合的修改方法,背景資料仍是數組,對數組的修改會影響到集合:

String[] countries = { "China", "Russia", "American" };List<String> asList3 = Arrays.asList(countries);countries[2] = "France";System.out.println(asList3);

列印:[China, Russia, France]

 

 

2.List轉成數組

而List轉成數組可以list的toArray(T[] array)方法,傳入類型完全一樣的數組,數組的大小傳list.size()。

List<String> fruits = new ArrayList<String>();fruits.add("Apple");fruits.add("Pear");fruits.add("Orange");String[] array = fruits.toArray(new String[fruits.size()]);

  

JAVA數組與List相互轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.