由于数组的大小不可变以及操作方法较小,对于同类型的多个对象,我们习惯使用集合来存放它们并存放。
常用的数组转List 的方法 Arrays.asList(T... a ); 传递多个可变参数,可转换成ArrayList 对象
一、案例,先来看两个方法
方法一:
public static void test1() {
List<Integer> list = Arrays.asList(1, 2, 3, 4);
list.set(1, 22);
list.add(5);
list.remove(1);
}
方法二:
public static void test2() {
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
list.set(1, 22);
list.add(5);
list.remove(1);
}
方法一中,list对象的add、remove操作都会操作失败,抛出java.lang.UnsupportedOperationException (不支持的操作异常),而set方法可以正常操作
方法二中,list对象的所有修改操作,都可以正常执行
二、浅析
原因是:Arrays.asList(1, 2, 3, 4) 返回的对象是 Arrays的内部类,继承了AbstractList,AbstractList中的set, add, remove 抽象方法中都是直接throw new UnsupportedOperationException(); 但内部类 ArrayList 并未重写父类的 add,remove方法。
所以,对Arrays.asList 在包装一层,使用方法二的方式,生成的List对象就是我们熟知的 ArrayList了
三、深析
Arrays.asList 方法的源码,注意英文文档注释的意思
/**
* 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");
* </pre>
*
* @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
*/
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
AbstractList的源码:
/**
* {@inheritDoc}
*
* <p>This implementation always throws an
* {@code UnsupportedOperationException}.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
* <p>This implementation always throws an
* {@code UnsupportedOperationException}.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
* <p>This implementation always throws an
* {@code UnsupportedOperationException}.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
throw new UnsupportedOperationException();
}