Sorting a list from an Arrays.asList () array also changes the original array?

I noticed strange behavior (for me) when sorting the list obtained with Arrays.asList(). It seems that after the Collections.sort( list )origin array is also sorted!

How is this possible?

List<Rate> rates = Arrays.asList( arrayRates );
Collections.sort( rates, new RateEffectiveDateComparator() );
/* after that the rates list AND arrayRates array are sorted in the same way */
+3
source share
1 answer

From the documentation of Arrays.asList ():

Returns a fixed size list supported by the specified array. (Changes to the "write through" return list to the array.)

The array you pass will be the array on which the list is based. When sorting a list, you actually sort the array. Check the source code Arrays.asList()...

+8

Source: https://habr.com/ru/post/1734075/


All Articles