UnsupportedOperationException

UnsupportedOperationException

本文介绍了为什么在尝试从列表中删除元素时会收到 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:返回由指定数组支持的固定大小列表.

你不能add到它;你不能删除.您不能在结构上修改 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 23:03