大清早的来了,把周五运行的代码一波,
出现异常
操作:把一个用逗号分隔字符串split成一个数组,我想转成list结果就来了一波Arrays.asList,而后又想对生成的list做添加,采用了add操作,结果就抛异常了----
结合网上查阅加原来看
1、Arrays.asList生成的list是否和我们平时使用的new ArrayList是否一致
/**
* 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);
}
Arrays的源码中也是返回的个new ArrayList,这就有点蒙蔽了,ctrl按住点ArrayList 结果是个Arrays里面内部类
返回的是这个内部类的ArrayList,但是这个继承自AbstractList这个抽象类,在AbstractList没有对add方法进行重写,而这个内部类的ArrayList也没有重写add方法,调用内部类的ArrayList的add方法相当于调用了父类AbstractList的add方法,源码一看,这直接就抛出了UnsupportedOperationException异常;
public boolean add(E e) { add(size(), e); return true; }
public void add(int index, E element) { throw new UnsupportedOperationException(); }
这就得再看看我们的java util里面的ArrayList了,也是继承自AbstractList,但是它重写了add方法
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
这样就不会调用到父类的直接抛出异常的add方法,无奈,只好把内部类的arrayList再转一遍到util中的arrayList,调用传参为集合的构造方法进行转换;
public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }
String str = "a,b,c,d";
String[] strArr = str.split(",");
List<String> list = Arrays.asList(strArr);
list.add("e");
//上面的代码会抛出异常 执行下面时,把上面一行的代码注释掉 //list.add("e");
List<String> utilList = new ArrayList(list);
utilList .add("e");
System.out.println(utilList.toString());
//运行结果
//[a, b, c, d, e]
Arrays.asList返回的arrayList根本就没有对add和remove方法重写,还是自己太菜,没踩过的坑,记录一下。