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
 
				
         
 
            
        基础教程推荐
- Java Swing计时器未清除 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				