1. 程式人生 > >java集合和數組互轉

java集合和數組互轉

參考 集合 rfi all spring https .com 進行 onu

方法一:使用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集合和數組互轉