Why do I get an UnsupportedOperationException when trying to remove an element from a List?

后端 未结 17 2144
后悔当初
后悔当初 2020-11-22 07:43

I have this code:

public static String SelectRandomFromTemplate(String template,int count) {
   String[] split = template.split(\"|\");
   List         


        
17条回答
  •  长情又很酷
    2020-11-22 07:55

    Quite a few problems with your code:

    On Arrays.asList returning a fixed-size list

    From the API:

    Arrays.asList: Returns a fixed-size list backed by the specified array.

    You can't add to it; you can't remove from it. You can't structurally modify the List.

    Fix

    Create a LinkedList, which supports faster remove.

    List list = new LinkedList(Arrays.asList(split));
    

    On split taking regex

    From the API:

    String.split(String regex): Splits this string around matches of the given regular expression.

    | 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:

    template.split("\\|")
    

    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.

    With this, your algorithm would be O(N).

提交回复
热议问题