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

后端 未结 17 2011
后悔当初
后悔当初 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 08:10

    Just read the JavaDoc for the asList method:

    Returns a {@code List} of the objects in the specified array. The size of the {@code List} cannot be modified, i.e. adding and removing are unsupported, but the elements can be set. Setting an element modifies the underlying array.

    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 with Arrays.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.

提交回复
热议问题