Arrays.asList gives UnsupportedOperationException

List

, returned Arrays.asList

, cannot be modified by methods such as add

or remove

. But if you pass it to the method Collections.sort

, it can sort the array without any problem (I was expecting an exception). This seems to be very inconsistent behavior. So what are the valid operations List

returned by the method asList

?

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 any information about this in the documentation.

Edit: Yes. I understand why he doesn't support remove

or add

. But then how can it support sorting?

+3


source to share


2 answers


Arrays.asList

returns a fixed size List

supported by an array. Therefore, remove

they are add

not supported. set

supported. You can look at this List

one as if it behaves exactly like an array. The array has a fixed length. You cannot add or remove elements, but you can assign values ​​to array indices, which is equivalent to a method set

List

. And you can sort the array.

Collections.sort(list)

does not resize List

, so you can sort the list of fixed sizes. All you need to sort List

is replace items List

. That's enough for that set(index,element)

.

All this information is in the Javadoc Arrays

:



/**
 * Returns a fixed-size list backed by the specified array.  (Changes to
 * the returned list "write through" to the array.)  This method acts
 * as bridge between array-based and collection-based APIs, in
 * combination with {@link Collection#toArray}.  The returned list is
 * serializable and implements {@link RandomAccess}.
 *
 * <p>This method also provides a convenient way to create a fixed-size
 * list initialized to contain several elements:
 * <pre>
 *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
 * </pre>
 *
 * @param a the array by which the list will be backed
 * @return a list view of the specified array
 */
 public static <T> List<T> asList(T... a)

      

And if you look at the implementation Collections.sort

, you can see that it actually sorts the array. The only method List

requires that List

was set

set

List

ListIterator

that calls the method List

set(index,element)

.

public static <T extends Comparable<? super T>> void sort(List<T> list) {
  Object[] a = list.toArray();
  Arrays.sort(a);
  ListIterator<T> i = list.listIterator();
  for (int j=0; j<a.length; j++) {
      i.next();
      i.set((T)a[j]);
  }
}

      

+8


source


Arrays.asList

gives List

under the array that you point to it . Fixed-size arrays. The wrapper List

supports the same operation as arrays, so you can reassign records, but you cannot change its length.



+1


source







All Articles