UnsupportedOperationException用list报错

问题描述:

学习List的过程中调用list的remove的方法出现了如下的错误:在这里插入图片描述
出现问题的代码
add方法也有相同的问题

@Override
	@Test
    public void ListTest(){
        List<Integer> iList = Arrays.asList(1, 2, 3);
        iList.remove(2);
    }

原因分析:

查看Arrays的asList方法:此方法new了一个ArrayList类

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

看看asList创造的是怎样的一个ArrayList类
发现了是在Arrays类中的ArrayList内部类(java.util.Arrays$ArrayList)
一般的ArrayList类是java.util.ArrayList

    public void ListTest(){
        List<Integer> iList = Arrays.asList(1, 2, 3);
		//iList.remove(2);
        System.out.println(iList.getClass().getName());
		//java.util.Arrays$ArrayList
    }
	//Arrays中的ArrayList类
    private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable

具体查看remove方法
抽象类AbstractList也就是这两个ArrayList的父类中的remove方法抛出了异常

	//抽象类AbstractList也就是这两个ArrayList的父类中的remove方法抛出了异常
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }

java.util.ArrayList能使用remove方法是因为其重写了remove方法
而java.util.Arrays$ArrayList则没有重写

    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

解决方案:

目前没有其他方案,只能使用util下的ArraysList

    @Test
    public void ListTest1(){
        ArrayList<Integer> iList = new ArrayList<>();
        System.out.println(iList.getClass().getName());
        iList.add(1);
        iList.add(2);
        iList.add(3);
        iList.remove(2);
    }

版权声明:本文为nidiquge原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。