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

后端 未结 17 1962
后悔当初
后悔当初 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:59

    Following is snippet of code from Arrays

    public static  List asList(T... a) {
            return new ArrayList<>(a);
        }
    
        /**
         * @serial include
         */
        private static class ArrayList extends AbstractList
            implements RandomAccess, java.io.Serializable
        {
            private static final long serialVersionUID = -2764017481108945198L;
            private final E[] a;
    

    so what happens is that when asList method is called then it returns list of its own private static class version which does not override add funcion from AbstractList to store element in array. So by default add method in abstract list throws exception.

    So it is not regular array list.

提交回复
热议问题