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
				
        
 
            
        - value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
 - 如何使用WebFilter实现授权头检查 2022-01-01
 - C++ 和 Java 进程之间的共享内存 2022-01-01
 - 将log4j 1.2配置转换为log4j 2配置 2022-01-01
 - 从 finally 块返回时 Java 的奇怪行为 2022-01-01
 - Jersey REST 客户端:发布多部分数据 2022-01-01
 - Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
 - Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
 - Eclipse 插件更新错误日志在哪里? 2022-01-01
 - Java包名称中单词分隔符的约定是什么? 2022-01-01
 
						
						
						
						
						