因为数组的大小不可变以及操做方法较小,对于同类型的多个对象,咱们习惯使用集合来存放它们并存放。javascript
经常使用的数组转List 的方法 Arrays.asList(T... a ); 传递多个可变参数,可转换成ArrayList 对象java
方法一:数组
public static void test1() { List<Integer> list = Arrays.asList(1, 2, 3, 4); list.set(1, 22); list.add(5); list.remove(1); }
方法二:dom
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方法能够正常操做ide
方法二中,list对象的全部修改操做,均可以正常执行url
缘由是:Arrays.asList(1, 2, 3, 4) 返回的对象是 Arrays的内部类,继承了AbstractList,AbstractList中的set, add, remove 抽象方法中都是直接throw new UnsupportedOperationException(); 但内部类 ArrayList 并未重写父类的 add,remove方法。spa
因此,对Arrays.asList 在包装一层,使用方法二的方式,生成的List对象就是咱们熟知的 ArrayList了code
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的源码:blog
/** * {@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(); }