相关疑难解决方法(0)

尝试从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, ", ");
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

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)
Run Code Online (Sandbox Code Playgroud)

这怎么会是正确的方法?Java.15

java exception list arraylist

444
推荐指数
7
解决办法
37万
查看次数

Arrays.asList()创建的List上的remove()抛出UnsupportedOperationException

我有一个集合c1<MyClass>和一个数组a<MyClass>.我试图将数组转换为集合c2并做c1.removeAll(c2),但这引发了UnsupportedOperationException.我发现asList()Arrays类返回了Arrays.ArrayList类,并且该类继承了其实现抛出的removeAll()from .AbstractList()UnsupportedOperationException

    Myclass la[] = getMyClass();
    Collection c = Arrays.asList(la);
    c.removeAll(thisAllreadyExistingMyClass);
Run Code Online (Sandbox Code Playgroud)

有没有办法删除元素?请帮忙

java

86
推荐指数
3
解决办法
3万
查看次数

标签 统计

java ×2

arraylist ×1

exception ×1

list ×1