java - Arrays.asList give UnsupportedOperationException -


the list returned arrays.aslist can't modified using methods such add or remove. if pass collections.sort method, can sort array without problem (i expected exception). seems inconsistent behaviour. allowed operations on list, returned aslist method?

list<integer> list = arrays.aslist(5,7, 10 , 8,9); list.remove(2);//exception  collections.sort(list);//ok, no exception sort... system.out.println(list); 

i couldn't find clue in documentation.

edit: yes can understand why doesn't support remove or add. how can support sorting?

arrays.aslist returns fixed size list backed array. therefore remove , add not supported. set supported. can @ list if behaves array. array has fixed length. can't add or remove elements, can assign values indices of array, equivalent set method of list. , can sort array.

collections.sort(list) doesn't change size of list, can sort fixed size list. need in order sort list swap elements of list. purpose set(index,element) sufficient.

all information found in javadoc of arrays :

/**  * returns fixed-size list backed specified array.  (changes  * returned list "write through" array.)  method acts  * bridge between array-based , collection-based apis, in  * combination {@link collection#toarray}.  returned list  * serializable , implements {@link randomaccess}.  *  * <p>this method provides convenient way create fixed-size  * list initialized contain several elements:  * <pre>  *     list&lt;string&gt; stooges = arrays.aslist("larry", "moe", "curly");  * </pre>  *  * @param array list backed  * @return list view of specified array  */  public static <t> list<t> aslist(t... a) 

and if @ implementation of collections.sort, see sorts array. list method requires modified list set of list's listiterator, calls list's set(index,element) method.

public static <t extends comparable<? super t>> void sort(list<t> list) {   object[] = list.toarray();   arrays.sort(a);   listiterator<t> = list.listiterator();   (int j=0; j<a.length; j++) {       i.next();       i.set((t)a[j]);   } } 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -