此代码运行出现 UnsupportedOperationException
public static void main(String[] args) {
Integer[] datas = {1,2,3,4,5};
List<Integer> list = Arrays.asList(datas);
list.add(5);
System.out.println(list.size());
}
看下源码找原因:Arrays类中asList()方法
可以看出 这是个固定size的list
/**
* Returns a fixed-size list backed by the specified array. (Changes to
* the returned list "write through" to the array.) This method acts
* as bridge between array-based and collection-based APIs, in
* combination with {@link Collection#toArray}. The returned list is
* serializable and implements {@link RandomAccess}.
*
* <p>This method also provides a convenient way to create a fixed-size
* list initialized to contain several elements:
* <pre>
* List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
*
* @param <T> the class of the objects in the array
* @param a the array by which the list will be backed
* @return a list view of the specified array
*/
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
ArrayList<>还是在Arrays类中属于私有内部类,该类继承抽象AbstractiList重写了很多方法但是没有add
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
继续看AbstractList
发现可变容量的list需要重写add方法
* <p>To implement a modifiable list, the programmer must additionally
* override the {@link #set(int, Object) set(int, E)} method (which otherwise
* throws an {@code UnsupportedOperationException}). If the list is
* variable-size the programmer must additionally override the
* {@link #add(int, Object) add(int, E)} and {@link #remove(int)} methods.
总结:Arrays工具类里的asList是数组和集合的桥梁,但不能直接进行元素添加
若需使用需要增加自动扩容的功能,可以参考如下例子
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Vanas
* @create 2020-03-21 9:50 下午
*/
public class Test {
public static void main(String[] args) {
Integer[] datas = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(datas);//固
List list1 = new ArrayList<>(list);
// list.add(5);
/*
java.lang.UnsupportedOperationException
*/
list1.add(5);
System.out.println(list1.size());
}
}