读Spring源码的时候看到asList这个函数,想了解一下,进行了一些资料查询,做一下记录。
API中是这么写的:
public static List asList(T… a)
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 Collection.toArray(). The returned list is serializable and implements RandomAccess.
This method also provides a convenient way to create a fixed-size list initialized to contain several elements:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
Parameters:
a - the array by which the list will be backed
Returns:
a list view of the specified array
对中间的描述进行简单翻译:
本方法根据给出的数组参数返回一个大小固定的List(对这个List的更改会被写回到数组中去)。这个方法作为数组API和集合API之间的桥梁,并与Collection.toArray()方法相结合。返回的List是可序列化的以及实现了随机访问。
该方法还提供了一个简便的创建大小固定的List的方法,只需用到几个元素进行初始化:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
asList使用的一些注意事项:
- 由API可以知道返回的List称得上是对数组的一个引用,对List或者数组的更改都会传递给另一方。
- 使用这个函数还需注意不能使用基本数据类型的数组作为参数,因为函数参数是泛型,故需要引用数据类型的数组作为参数,若使用基本数据类型数组则会将该数组作为单个元素存进List中(因为数组也是引用数据类型)。若要使用基本数据类型数组,只能使用它们的包装类数组。
- 该List不能使用add()和remove()函数,虽然他有这两个函数,因为它的大小是固定的,所以这两个函数只有定义而没有实现,使用这两个函数会报java.lang.UnsupportedOperationException错误
- 可以通过创建一个ArrayList对象并以List作为参数使用addAll函数,就可以获得一个可以add和remove的列表了。如:
Integer[] array = new Integer[]{1,2,3,4,5};
List<Integer> list = new ArrayList<Integer>();
list.addAll(Arrays.asList(array));