Why do I get an UnsupportedOperationException when trying to remove an element from a List?(尝试从列表中删除元素时,为什么会收到 UnsupportedOperationException?)
问题描述
我有这个代码:
public static String SelectRandomFromTemplate(String template,int count) {
String[] split = template.split("|");
List<String> list=Arrays.asList(split);
Random r = new Random();
while( list.size() > count ) {
list.remove(r.nextInt(list.size()));
}
return StringUtils.join(list, ", ");
}
我明白了:
06-03 15:05:29.614: ERROR/AndroidRuntime(7737): java.lang.UnsupportedOperationException
06-03 15:05:29.614: ERROR/AndroidRuntime(7737): at java.util.AbstractList.remove(AbstractList.java:645)
这怎么会是正确的方法?Java.15
How would be this the correct way? Java.15
推荐答案
你的代码有不少问题:
来自 API:
Arrays.asList
:返回由指定数组支持的固定大小列表.
你不能添加
到它;你不能从中 remove
.您不能在结构上修改 List
.
You can't add
to it; you can't remove
from it. You can't structurally modify the List
.
创建一个LinkedList
,它支持更快的remove
.
Create a LinkedList
, which supports faster remove
.
List<String> list = new LinkedList<String>(Arrays.asList(split));
<小时>
关于split
采用正则表达式
来自 API:
On split
taking regex
From the API:
String.split(String regex)
:围绕给定 正则表达式.
|
是一个正则表达式元字符;如果要在文字 |
上进行拆分,则必须将其转义为 |
,它作为 Java 字符串文字是 "\|"
.
|
is a regex metacharacter; if you want to split on a literal |
, you must escape it to |
, which as a Java string literal is "\|"
.
template.split("\|")
<小时>
关于更好的算法
与其使用随机索引一次调用 remove
一个,不如在范围内生成足够多的随机数,然后使用 遍历
,在适当的索引处调用 List
一次>listIterator()remove()
.关于如何在给定范围内生成随机但不同的数字,stackoverflow 上有一些问题.
On better algorithm
Instead of calling remove
one at a time with random indices, it's better to generate enough random numbers in the range, and then traversing the List
once with a listIterator()
, calling remove()
at appropriate indices. There are questions on stackoverflow on how to generate random but distinct numbers in a given range.
有了这个,你的算法将是 O(N)
.
With this, your algorithm would be O(N)
.
这篇关于尝试从列表中删除元素时,为什么会收到 UnsupportedOperationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:尝试从列表中删除元素时,为什么会收到 Unsupp


基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01