Collection sort

GDK docs show that Collection.sort (comparator comparator) does not change the collection to which it is called, but the code below indicates something else. Is this an implementation error, a document error, or a misunderstanding on my part?

class ISO3LangComparator implements Comparator<Locale> {

    int compare(Locale locale1, Locale locale2) {
        locale1.ISO3Language <=> locale2.ISO3Language
    }
}

List<Locale> locales = [Locale.FRENCH, Locale.ENGLISH]
def sortedLocales = locales.sort(new ISO3LangComparator())

// This assertion fails
assert locales[0] == frenchLocale
+3
source share
1 answer

the documentation states:

If the collection is a list, it is sorted by place and returned. Otherwise, the items are first placed in a new list, which is then sorted and returned - leaving the original collection unchanged.

which is reflected in the implementation of the sort () method

public static <T> List<T> sort(Collection<T> self, Comparator<T> comparator) {
  List<T> list = asList(self);
  Collections.sort(list, comparator);
  return list;
}

asList , java.util.List. , , java.util.ArrayList.

[], java.util.List.

+2

All Articles