尝试从List中删除元素时,为什么会出现UnsupportedOperationException? [英] Why do I get an UnsupportedOperationException when trying to remove an element from a List?

查看:98
本文介绍了尝试从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

推荐答案

您的代码存在一些问题:

Quite a few problems with your code:

从API:


Arrays.asList :返回由指定数组支持的固定大小列表

你不能添加;你不能从中删除。您不能在结构上修改列表

You can't add to it; you can't remove from it. You can't structurally modify the List.

创建一个 LinkedList ,它支持更快删除

Create a LinkedList, which supports faster remove.

List<String> list = new LinkedList<String>(Arrays.asList(split));






On split 参加正则表达式



来自API:


On split taking regex

From the API:


String.split(String regex) :围绕给定正则表达式

| 是一个正则表达式元字符;如果要拆分文字 | ,则必须将其转义为 \ | ,它作为Java字符串literal是\\ |

| 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("\\|")






更好的算法



而不是调用删除一次一个随机索引,最好在范围内生成足够的随机数,然后使用 listIterator()遍历 List 一次,在适当的索引处调用 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)

这篇关于尝试从List中删除元素时,为什么会出现UnsupportedOperationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆