From the Java documentation for Arrays.asList :
Returns a fixed size list supported by the specified array. (Changes to the "write through" list returned to the array.) This method acts as a bridge between the array-based API and the collection in combination with Collection.toArray() . The returned list is serializable and implements RandomAccess .
So, when you change something in the list, it โwritesโ to the base array, ar , which is also the base array in the sort, so the change is reflected in the sort.
In addition, the code for asList :
public static <T> List<T> asList(T... a) { return new ArrayList<T>(a); }
This is java.util.Arrays.ArrayList , which has the following definition:
ArrayList(E[] array) { a = Objects.requireNonNull(array); }
The important thing is that a not copied, it is the original array. The java.util.ArrayList class has the following constructor
public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); }
therefore, in the java.util.ArrayList constructor, we create copies of each element, and in java.util.Arrays.ArrayList we do not.
Sunde source share