记录一个问题: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所有的特性了,所以操作就不会报错了。

猜你喜欢

转载自blog.csdn.net/qq_37256896/article/details/103169765