Created two lists from one array, changing one list, changing another

I created two lists from one array and sorted one of them. When I tried to change one list, another list was also updated.

List<Integer> list = Arrays.asList(ar); List<Integer> sorted = Arrays.asList(ar); Collections.sort(sorted); list.set(0,10000000); //changes sorted also 

It took me a while to figure out how the code below works.

List<Integer> sorted = new ArrayList<Integer>(Arrays.asList(ar));

I want to know why my first approach did not work? I created two separate lists of why changes occur in both of them. How does java assign values โ€‹โ€‹to variables here?

+5
source share
3 answers

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.

+11
source

Arrays have their own ArrayList implementations that do not make an array copy from the toList list

+1
source

A list is a collection of objects, and both lists are collections of the same objects. The set statement modifies the object, and the object is separated by both lists.

I do not understand why the second version works.

+1
source

All Articles