java 数组转List

(1)Arrays.asList(arr)

注:此方法得到的list是静态类ArrayList,没有覆盖父类的add, remove等方法,所以如果直接调用,会报UnsupportedOperationException异常。

(2)Arrays.stream(arr).collect(Collectors.toList())

Integer[] data1 = {1, 2, 3, 4};
	    List<Integer> list = Arrays.stream(data1).collect(Collectors.toList());
	    System.out.println(list); // [1, 2, 3, 4]
	    
	    String[] data2 = {"huo", "ming", "jing", "chao"};
	    List<String> list2 = Arrays.stream(data2).collect(Collectors.toList());
	    list2.add("qiao");
	    System.out.println(list2); // [huo, ming, jing, chao, qiao]
	    System.out.println(Arrays.asList(data2));//[huo, ming, jing, chao]
	    System.out.println(Arrays.asList(data2).getClass());//class java.util.Arrays$ArrayList
	    ArrayList al = (ArrayList) Arrays.asList(data2);//报错:java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
	    al.add("ren");
	    System.out.println(al);

其中,Arrays和Collectors都来自 java.util包

import java.util.stream.Collectors;
import java.util.Arrays;

相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页