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

偶尔善良 提交于 2019-12-14 03:47:23

问题


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 */

回答1:


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()...



来源:https://stackoverflow.com/questions/2318855/sort-a-list-from-arrays-aslist-changes-also-the-origin-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!