为什么我试图从列表中删除时得到UnsupportedOperationException异常? [英] Why I get UnsupportedOperationException when trying to remove from the List?

查看:170
本文介绍了为什么我试图从列表中删除时得到UnsupportedOperationException异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code:

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

推荐答案

与code不少问题:

从API:

<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#asList%28T...%29\"><$c$c>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));


拆分以正则表达式

从API:


On split taking regex

From the API:

<一个href=\"http://java.sun.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29\"><$c$c>String.split(String正则表达式) :拆分围​​绕给定的regular前pression

| 是一个正则表达式元字符;如果你想拆就字面 | ,则必须将其逃到 \\ | ,它作为一个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("\\|")


在更好的算法

而不是调用的删除逐一随机指标时,最好在范围内产生足够的随机数,然后遍历列表一旦与的ListIterator(),要求删除()在适当的指数。还有如何在给定范围内随机产生,但不同数字上计算器的问题。


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异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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