I have this 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 get this:
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)
How would be this the correct way? Java.15
Just read the JavaDoc for the asList method:
This is from Java 6 but it looks like it is the same for the android java.
EDIT
The type of the resulting list is
Arrays.ArrayList
, which is a private class inside Arrays.class. Practically speaking, it is nothing but a List-view on the array that you've passed withArrays.asList
. With a consequence: if you change the array, the list is changed too. And because an array is not resizeable, remove and add operation must be unsupported.I've got another solution for that problem:
work on
newList
;)Probably because you're working with unmodifiable wrapper.
Change this line:
to this line:
Quite a few problems with your code:
On
Arrays.asList
returning a fixed-size listFrom the API:
You can't
add
to it; you can'tremove
from it. You can't structurally modify theList
.Fix
Create a
LinkedList
, which supports fasterremove
.On
split
taking regexFrom the API:
|
is a regex metacharacter; if you want to split on a literal|
, you must escape it to\|
, which as a Java string literal is"\\|"
.Fix:
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 theList
once with alistIterator()
, callingremove()
at appropriate indices. There are questions on stackoverflow on how to generate random but distinct numbers in a given range.With this, your algorithm would be
O(N)
.I think that replacing:
with
resolves the problem.
The list returned by
Arrays.asList()
might be immutable. Could you try