天天看點

java中數組轉集合_Java中數組與集合的互相轉換

數組與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 stringList = Arrays.asList(strs);

System.out.println(stringList);

//1.1注意:直接使用add、remove、clear方法會報錯

// stringList.add("abc");

//1.2如果想要正常的使用add等修改方法,需要重新new一個ArrayList

List trueStringList = new ArrayList<>(Arrays.asList(strs));

trueStringList.add("abc");

System.out.println(trueStringList);

//2.集合轉數組

List 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));

}

}