記錄一個問題:Exception in thread “main” java.lang.UnsupportedOperationException

在這裏插入圖片描述
在開發中遇到了這樣的一個問題,後臺報錯空指針異常,但是這個空指針異常是在remove()方法中產生的,那麼必將去探尋他的原因啊,
Exception in thread “main” java.lang.UnsupportedOperationException
以前在使用array轉list的時候基本上沒有去使用過remove,add這些方法,或許是以前沒遇到這樣的要操作remove,add,這些操作,所以不太注意,但是這次遇到了別人寫的bug了那麼咱是不是要更正過來呢。
常常使用Arrays.asLisvt()後調用add,remove這些method時出現java.lang.UnsupportedOperationException異常。這是由於:
Arrays.asLisvt() 返回java.util.ArraysArrayList, 而不是ArrayList。ArraysArrayList和ArrayList都是繼承AbstractList,remove,add等method在AbstractList中是默認throw UnsupportedOperationException而且不作任何操作。ArrayList override這些method來對list進行操作,但是Arrays$ArrayList沒有override remove(int),add(int)等,所以throw UnsupportedOperationException。
解決方法是使用Iterator,或者轉換爲ArrayList,那麼既然會存在這樣的異常那麼我們也不要使用iterator方法了,避免以後操作再次採坑,所以咱們直接給徹底解決這bug。具體解決方式請看下面的代碼分析。

List list = Arrays.asList(a[]);
List arrayList = new ArrayList(list);

解決方法先看下源碼:

/* 
* @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);
}

/**
 * @serial include
 */
private static class ArrayList<E> extends AbstractList<E>
    implements RandomAccess, java.io.Serializable
{
    private static final long serialVersionUID = -2764017481108945198L;
    private final E[] a;

    ArrayList(E[] array) {
        a = Objects.requireNonNull(array);
    }

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

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

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

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

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

    @Override
    public int indexOf(Object o) {
        E[] a = this.a;
        if (o == null) {
            for (int i = 0; i < a.length; i++)
                if (a[i] == null)
                    return i;
        } else {
            for (int i = 0; i < a.length; i++)
                if (o.equals(a[i]))
                    return i;
        }
        return -1;
    }

    @Override
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

    @Override
    public Spliterator<E> spliterator() {
        return Spliterators.spliterator(a, Spliterator.ORDERED);
    }

    @Override
    public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        for (E e : a) {
            action.accept(e);
        }
    }

    @Override
    public void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        E[] a = this.a;
        for (int i = 0; i < a.length; i++) {
            a[i] = operator.apply(a[i]);
        }
    }

    @Override
    public void sort(Comparator<? super E> c) {
        Arrays.sort(a, c);
    }
}

在這個內部類中沒有這個List接口中的remove,add,這些方法,但是使用List接收並不會出錯,因爲所有的在運行時都會向上轉型。(轉型後具有了其他的特性,編譯不提示出錯,運行時出錯),運行時發現沒有這些方法,出現異常。

// array轉list不支持remove add 這裏的 list是Array中的內部類
List<String> lastChildIdsArray = Arrays.asList(lastChildIds);
// 需要使用 new 出一個新的Arraylist來接收新的的參數
List<String> lastChildIdslist = new ArrayList(lastChildIdsArray);

因爲這裏的返回的是一個arraylist

public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

這個ArrayList t是繼承的AbstractList,AbstractList又實現了List接口:

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> 

//Arraylist類
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{

所以這裏是可以用來接收的。並且可以轉換爲一個Arraylist,那麼當new 出一個Arraylist時怎樣又能接收一個參數了呢(參數類型:和arraylist一個類型也就是List接口類型,或者list的子類)

/**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    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;
        }
    }

實際上是一個Collection或其子類而List又是Collection的子類

public interface List<E> extends Collection<E> {

所以是成立的。這樣的話就是一個真正的list了,那麼就具有了arraylist所有的特性了,所以操作就不會報錯了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章