【问题标题】:java.lang.UnsupportedOperationException when calling List.remove(index) [duplicate]java.lang.UnsupportedOperationException 调用 List.remove(index) [重复]
【发布时间】:2013-01-03 09:44:15
【问题描述】:

可能重复:
Why I get UnsupportedOperationException when trying to remove from the List?

当我调用 List.remove(index) 或 list.remove(element) 时,它会引发 java.lang.UnsupportedOperationException。唯一相关的错误代码是这样的:

17:08:10 [SEVERE]       at java.util.AbstractList.remove(Unknown Source)

这是一个例子:

String line = "cmd /say This is a test";
String[] segments = line.split(" ");
String cmd = segments[0];
List rest = Arrays.asList(segments);
rest.remove(0); // This line raises the exception

有人知道为什么会这样吗?在我的实际代码中,我检查了索引 0 处的元素要删除。

【问题讨论】:

    标签: java arrays list exception arraylist


    【解决方案1】:

    来自Arrays.asList()的JavaDoc:

    返回由指定数组支持的固定大小的列表。 (更改为 返回的列表“写入”到数组。)

    所以不是固定大小的列表:

    List rest = Arrays.asList(segments);
    

    创建一个新的可变大小列表:

    List<String> rest = new ArrayList<String>(Arrays.asList(segments));
    

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 1970-01-01
      • 2021-06-27
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 2017-09-29
      • 2020-02-02
      相关资源
      最近更新 更多