java - Why do I get an UnsupportedOperationException when trying to remove an element from a List? -
i have 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, ", "); }
i this:
06-03 15:05:29.614: error/androidruntime(7737): java.lang.unsupportedoperationexception 06-03 15:05:29.614: error/androidruntime(7737): @ java.util.abstractlist.remove(abstractlist.java:645)
how correct way? java.15
quite few problems code:
on arrays.aslist
returning fixed-size list
from api:
arrays.aslist
: returns fixed-size list backed specified array.
you can't add
it; can't remove
it. can't structurally modify list
.
fix
create linkedlist
, supports faster remove
.
list<string> list = new linkedlist<string>(arrays.aslist(split));
on split
taking regex
from api:
string.split(string regex)
: splits string around matches of given regular expression.
|
regex metacharacter; if want split on literal |
, must escape \|
, java string literal "\\|"
.
fix:
template.split("\\|")
on better algorithm
instead of calling remove
1 @ time random indices, it's better generate enough random numbers in range, , traversing list
once listiterator()
, calling remove()
@ appropriate indices. there questions on stackoverflow on how generate random distinct numbers in given range.
with this, algorithm o(n)
.
Comments
Post a Comment