數組與List的相互轉換
- List轉數組:采用集合的toArray()方法
- 數組轉List:采用Arrays的asList()方法
數組轉換為集合
注意:在數組轉集合的過程中,要注意是否使用了視圖的方式直接返回數組中的數據。以Arrays.asList()為例,它把數組轉換成集合時,不能使用其修改集合相關的方法,它的add/remove/clear方法會拋出 UnsupportedOperationException異常。
這是因為Arrays.asList體現的是適配器模式,后台的數據仍是原有數組。asList的返回對象是一個Arrays的內部類,它並沒有實現集合個數的相關修改操作,這也是拋出異常的原因。
集合轉數組
集合轉數組相對簡單,一般在適配別人接口的時候常常用到
代碼例子
public class Main {
public static void main(String[] args) {
//1.數組轉換為集合
String[] strs = new String[3];
strs[0] = "a";
strs[1] = "b";
strs[2] = "c";
List<String> stringList = Arrays.asList(strs);
System.out.println(stringList);
//1.1注意:直接使用add、remove、clear方法會報錯
// stringList.add("abc");
//1.2如果想要正常的使用add等修改方法,需要重新new一個ArrayList
List<String> trueStringList = new ArrayList<>(Arrays.asList(strs));
trueStringList.add("abc");
System.out.println(trueStringList);
//2.集合轉數組
List<Integer> integerList = new ArrayList<>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
//新生成的數組大小一定要大於原List的大小
Integer[] integers = new Integer[3];
integerList.toArray(integers);
System.out.println(Arrays.asList(integers));
}
}