【问题标题】:Interface List method add(int index, E element); Why i have UnsupportedOperationEception? [duplicate]接口 List 方法 add(int index, E element);为什么我有 UnsupportedOperationEception? [复制]
【发布时间】:2016-12-31 19:47:59
【问题描述】:

我正在制作单元测试接口列表。简单的代码但我无法理解,为什么testAdd() 会抛出 UnsupportedOperationException 而testSet() 不会抛出此异常。

public class testList {
    private static List<Integer> testList = new ArrayList<>();

    public static void main(String[] args) {
        init();
        testGet();
        testSet();
        testAdd();
    }

    private static void init() {
        testList = Arrays.asList(0, 1, 2, 3, 1, 2, 5, 4);
    }

    private static void testGet() {
        assertEquals(Integer.valueOf(2), testList.get(2));
    }

    private static void testSet() {
        testList.set(6, 5);
        assertEquals(new Integer[]{0, 1, 2, 3, 1, 2, 5, 4}, testList.toArray());
    }

    private static void testAdd() {
        testList.add(0, 1);
        assertEquals(new Integer[]{1, 0, 2, 2, 3, 3, 4, 5, 4}, testList.toArray());
    }
}

这是来自 AbstractList

【问题讨论】:

  • 我只想指出testAdd 无论如何都应该失败
  • @cricket_007 是的,抱歉,这只是总测试的一部分 :)

标签: java list testing collections


【解决方案1】:

Arrays.toList(T... t)rerun a java.util.Arrays.ArrayList not java.util.ArrayList

这个类是一个添加方法是AbstractList的扩展 喜欢这段代码

public void add(int index, E element) {
    throw new UnsupportedOperationException();
}

所以抛出 UnsupportedOperationException

【讨论】:

  • 最好在代码块之外提供一些文本来解释您要显示的内容
  • 对不起,我是一只小蛇
【解决方案2】:
Arrays.asList

将包装器返回到原始列表,因此您将无法更改列表长度(add()remove())。

【讨论】:

  • 你完全正确。我会更新我的答案
  • 另外,在您尝试回答问题之前,请尽量查找重复项。尤其是这个问题已经被问和回答了数百次。相反,标记(或在您有足够声誉后投票)以关闭。
猜你喜欢
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 2012-11-10
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多