Arrays.asList返回ArrayList并非java.util.ArrayList,调用报 UnsupportedOperationException

阅读更多
调用代码:
String[] tmpIds = ids.split(",");
rt = Arrays.asList(tmpIds);
rt.add(String.valueOf(userId));

Arrays.asList(tmpIds)返回固定大小的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}.
     *
     * 
     *
     * 

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");
     * 
* * @param a the array by which the list will be backed * @return a list view of the specified array */ public static List asList(T... a) { return new ArrayList(a); }

注:asList返回固定大小的list,对list中元素的改变将“同步”到原数组。

调用add方法报UnsupportedOperationException异常,实际add方法调用的是java.util.AbstractList的add方法,如下:
 public void add(int index, E element) {
     throw new UnsupportedOperationException();
 }


查考jdk源码如下:
public class Arrays {
//...............
//...............
    public static  List asList(T... a) {
        return new ArrayList(a);
    }
//...............
//...............
    private static class ArrayList extends AbstractList
	implements RandomAccess, java.io.Serializable
    {
        private static final long serialVersionUID = -2764017481108945198L;
	private final E[] a;

	ArrayList(E[] array) {
            if (array==null)
                throw new NullPointerException();
	    a = array;
	}

	public int size() {
	    return a.length;
	}

	public Object[] toArray() {
	    return a.clone();
	}

	public  T[] toArray(T[] a) {
	    int size = size();
	    if (a.length < size)
		return Arrays.copyOf(this.a, size,
				     (Class) a.getClass());
	    System.arraycopy(this.a, 0, a, 0, size);
	    if (a.length > size)
		a[size] = null;
	    return a;
	}

	public E get(int index) {
	    return a[index];
	}

	public E set(int index, E element) {
	    E oldValue = a[index];
	    a[index] = element;
	    return oldValue;
	}

        public int indexOf(Object o) {
            if (o==null) {
                for (int i=0; i 
 
调用报 java.lang.UnsupportedOperationException

你可能感兴趣的:(Java,JDK)