简体   繁体   English

Collections.sort

[英]Collections.sort

Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager)); Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager)); This is a sort function.The first parameter is an array to be sorted.这是一个排序 function。第一个参数是一个要排序的数组。 Why we need the second parameter?What can the second parameter do?为什么我们需要第二个参数?第二个参数可以做什么?

Sort the second argument isComparable so you can provide custom function for comparing the object. 排序第二个参数是Comparable ,因此您可以提供自定义 function 来比较 object。

Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager)); Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));

It's seems this uses a comparator that compares objects by display name.似乎这使用了一个比较器,该比较器按显示名称比较对象。

apps is a list of ResolveInfo objects. appsResolveInfo对象的列表。 ResolveInfo isn't Comparable , meaning that because it doesn't implement Comparable interface, there is no "rule" on how to compare two ResolveInfo objects. ResolveInfo不是Comparable ,这意味着因为它没有实现Comparable接口,所以没有关于如何比较两个ResolveInfo对象的“规则”。 sort(List<T> list) method requires objects in the list to be comparable: sort(List<T> list)方法要求列表中的对象具有可比性:

public static <T extends Comparable<? super T>> void sort(List<T> list)

DisplayNameComparator defines logic on how to compare ResolveInfo objects by the display names of apps they represent. DisplayNameComparator定义了如何通过它们所代表的应用程序的显示名称来比较ResolveInfo对象的逻辑。

Source code:源代码:

  public static class DisplayNameComparator
        implements Comparator<ResolveInfo> {
    public DisplayNameComparator(PackageManager pm) {
        mPM = pm;
        mCollator.setStrength(Collator.PRIMARY);
    }

    public final int compare(ResolveInfo a, ResolveInfo b) {
        CharSequence  sa = a.loadLabel(mPM);
        if (sa == null) sa = a.activityInfo.name;
        CharSequence  sb = b.loadLabel(mPM);
        if (sb == null) sb = b.activityInfo.name;

        return mCollator.compare(sa.toString(), sb.toString());
    }

    private final Collator   mCollator = Collator.getInstance();
    private PackageManager   mPM;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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