Arrays.asList give UnsupportedOperationException [duplicate]

Arrays.asList returns a fixed size List backed by an array. Therefore remove and add are not supported. set is supported. You can look at this List as if it behaves exactly like an array. An array has a fixed length. You can’t add or remove elements, but you can assign values to the indices of the array, which is equivalent to the set method of List. And you can sort an array.

Collections.sort(list) doesn’t change the size of the List, so is can sort a fixed size list. All you need in order to sort a List is to swap elements of the List. For this purpose set(index,element) is sufficient.

All this information is found in the Javadoc of 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 an implementation of Collections.sort, you see that it actually sorts an array. The only List method it requires that modified the List is set of the List‘s ListIterator, which calls the List‘s set(index,element) method.

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]);
  }
}

Leave a Comment