简体   繁体   中英

Sort a list from Arrays.asList() changes also the origin array?

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

How is it 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 */

From the documentation of Arrays.asList():

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

The array you pass will be the array the list is based on. When sorting the list, you are actually sorting the array. Check the sourcecode of Arrays.asList() ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM