开发者

collection sorting

The GDK docs indicate that Collection.sort(Comparator comparator) does not change the collection it is called on, but the code below indicates otherwise. Is this a bug in the implementation, error in the docs, 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.开发者_如何学CENGLISH]
def sortedLocales = locales.sort(new ISO3LangComparator())

// This assertion fails
assert locales[0] == frenchLocale


the documentation states:

If the Collection is a List, it is sorted in place and returned. Otherwise, the elements are first placed into 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;
}

the asList method looks whether the given collection is an instanceof java.util.List. If yes, it returns the reference, if not it returns a new java.util.ArrayList instance.

since you are using the [] syntax you are implicitly working with an instance of java.util.List.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜