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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
回答: 引发异常"Exception in thread "main" java.lang.UnsupportedOperationException: remove"的原因是在调用Arrays.asList()方法生成的List对象上调用了add或remove方法。\[2\]Arrays.asList()返回的是Arrays的内部类ArrayList,而不是java.util.ArrayListArrays的内部类ArrayList继承自AbstractList,而AbstractList中的remove和add方法默认会抛出UnsupportedOperationException异常。\[3\]解决这个问题的方法是将Arrays.asList()生成的List对象转换为java.util.ArrayList对象,然后再进行add或remove操作。例如,可以使用以下代码解决这个问题: ``` String\[\] array = {"1","2","3","4","5"}; List<String> list = Arrays.asList(array); List<String> arrList = new ArrayList<>(list); arrList.add("6"); ``` #### 引用[.reference_title] - *1* *3* [java.lang.UnsupportedOperationException解决方法!!!](https://blog.csdn.net/lcdaaaa/article/details/80240030)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [java:Exception in threadmainjava.lang.UnsupportedOperationException](https://blog.csdn.net/qq_44732146/article/details/125866796)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kay三石 [Alay Kay]

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值