java集合和數組互轉

來源:互聯網
上載者:User

標籤:collect   java集合   www   注意   ons   asList   []   增加   轉換   

方法一:使用Arrays.asList()方法
String[] strs = {"one","two","three"};
List<String> strList = Array.asList(strs);
注意:
1)這個方法返回的是基於數組的List視圖,並未正在的建立List對象,所以不能對List進行增加和刪除操作,
進行修改List是,同樣會修改到數組。
2)數群組轉換成唯讀List,使用Collections.unmodifiableList()方法來將數群組轉換為List。
3)返回可增刪改的List,使用new ArrayList(Array.asList(array))。

方法二:使用Collections.addAll()方法
String[] strs = {"one","two","three"};
List<String> list = new ArrayList();
Collections.addAll(list,strs);
注意:
該方法相當於一個添加操作,把數組strs中的元素添加到集合list中,不會覆蓋集合list中的原有元素。

方法三:使用Spring架構的CollectionUtils.arrayToList()方法
String[] strs = {"one","two","three"};
List<String> list = CollectionUtils.arrayToList(strs);

將ArrayList轉換成數組
使用toArray()方法
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("one");
arrayList.add("two");
String strs = arrayList.toArray(new String[0]);//集合轉換成數組

更詳細,請參考:
https://www.cnblogs.com/GarfieldEr007/p/7082945.html

java集合和數組互轉

聯繫我們

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