public static void test1(){
// 1、不能直接使用asList来转换基本类型数组
int[] arr = {1, 2, 3};
List list = Arrays.asList(arr);
System.out.printf("list:%s size:%s class:%s", list, list.size(), list.get(0).getClass());
}
输出结果:
list:[[I@27f8302d] size:1 class:class [I
原因:
查看源码可以看到,接收入参为泛型,而基本类型并没有集成Object
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
解决方法:
进行装箱或者直接使用包装类型
public static void test1(){
// 1、不能直接使用asList来转换基本类型数组
Integer[] arr = {1, 2, 3};
List list = Arrays.asList(arr);
System.out.printf("list:%s size:%s class:%s", list, list.size(), list.get(0).getClass());
}
list:[1, 2, 3] size:3 class:class java.lang.Integer
public static void test2(){
String[] arr = {"1", "2", "3"};
List list = Arrays.asList(arr);
try {
list.add("4");
} catch (Exception e){
e.printStackTrace();
}
System.out.printf("arr:%s, list:%s", Arrays.toString(arr), list);
}
输出结果:
报了不支持的操作异常
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.ooamo.test.AsListTest.test2(AsListTest.java:25)
at com.ooamo.test.AsListTest.main(AsListTest.java:11)
arr:[1, 2, 3], list:[1, 2, 3]
原因:
查看源码可以看到,asList返回到ArrayList是一个内部类,继承了AbstractList,再查看源码,并没有是哪set,add,remove方法
解决方法:
asList之后new一个List给他
public static void test2(){
String[] arr = {"1", "2", "3"};
List list = new ArrayList(Arrays.asList(arr));
try {
list.add("4");
} catch (Exception e){
e.printStackTrace();
}
System.out.printf("arr:%s, list:%s", Arrays.toString(arr), list);
}
public static void test3(){
String[] arr = {"1", "2", "3"};
List list = Arrays.asList(arr);
arr[0] = "0";
System.out.printf("arr:%s, list:%s", Arrays.toString(arr), list);
}
输出结果:
arr:[0, 2, 3], list:[0, 2, 3]
原因:
两者为同个引用
解决方法:
new一个新的List
public static void test3(){
String[] arr = {"1", "2", "3"};
List list = new ArrayList(Arrays.asList(arr));
arr[0] = "0";
System.out.printf("arr:%s, list:%s", Arrays.toString(arr), list);
}
arr:[0, 2, 3], list:[1, 2, 3]