简体   繁体   English

关于Collections.sort的困惑(列表 <T> 列表,比较器 <? super T> c)例子

[英]Confusion about Collections.sort(List<T> list, Comparator<? super T> c) example

Here is the code 这是代码

   import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Dog implements Comparator<Dog>, Comparable<Dog> {
    private String name;
    private int age;

    Dog() {
    }

    Dog(String n, int a) {
        name = n;
        age = a;
    }

    public String getDogName() {
        return name;
    }

    public int getDogAge() {
        return age;
    }

    // Overriding the compareTo method
    public int compareTo(Dog d) {
        return (this.name).compareTo(d.name);
    }

    // Overriding the compare method to sort the age
    public int compare(Dog d, Dog d1) {
        return d.age - d1.age;
    }
}

public class Main {

    public static void main(String args[]) {
        // Takes a list o Dog objects
        List<Dog> list = new ArrayList<Dog>();

        list.add(new Dog("Shaggy", 3));
        list.add(new Dog("Lacy", 2));
        list.add(new Dog("Roger", 10));
        list.add(new Dog("Tommy", 4));
        list.add(new Dog("Tammy", 1));
        Collections.sort(list);// Sorts the array list

        for (Dog a : list)
            // printing the sorted list of names
            System.out.print(a.getDogName() + ", ");

        // Sorts the array list using comparator
        Collections.sort(list, new Dog());
        System.out.println(" ");
        for (Dog a : list)
            // printing the sorted list of ages
            System.out.print(a.getDogName() + "  : " + a.getDogAge() + ", ");
    }
}

I know that the 2-argument sort method here takes the arguments of type List and a Comparator. 我知道这里的2参数排序方法采用List类型和Comparator类型的参数。 But here when we pass the list Dog and a new Object of Dog, I just don't understand what is happening in the compare() method? 但是在这里,当我们传递列表Dog和Dog的新Object时,我只是不明白compare()方法中正在发生什么? ie

return d1.age - d2.age;

What does this signify? 这意味着什么? And if I do 如果我愿意

return d1.age + d2.age; 

why does it change the ordering? 为什么更改顺序?

A good practice is to write such compare methods using Integer.compare() method: 一个好的做法是使用Integer.compare()方法编写这样的比较方法:

public int compare(Dog d, Dog d1) {
  return Integer.compare(d.age, d1.age);
}

I think, this way it is much more obvious, what is going on here. 我认为,这种方式更明显了。 (Also, this way is safer.) (而且,这种方式更安全。)

for d1.age - d2.age d1.age - d2.age

  • if negative number, then d1 is logically less than d2 in sort order 如果为负数,则d1按排序顺序在逻辑上小于d2
  • if positive, then d1 is logically greather than d2 in sort order 如果为正,则d1在逻辑上比d2大
  • if 0, then objects are equal 如果为0,则对象相等

You can refer the javadoc for compare method 您可以参考javadoc的compare方法

So when you are sorting dogs, and your compare method is comparing their ages, hence Tammy is less than Lacy according to the your method implementation. 因此,当您对狗进行分类并且您的比较方法正在比较它们的年龄时,根据您的方法实现, Tammy小于Lacy

Making Dog implement both Comparable and Comparator seems like a bad idea to me. 让Dog同时实现ComparableComparator对我来说似乎是个坏主意。

  • Collections.sort(list) will cause compareTo() method to be invoked Collections.sort(list)将导致compareTo()方法被调用
  • Collections.sort(list, new Dog()) will cause compare() method to be invoked Collections.sort(list, new Dog())将导致compare()方法被调用

I believe you should look into sorting user defined object using Comparable and Comparator 我相信您应该研究使用ComparableComparator对用户定义的对象进行排序

Your class (Dog) implements both Comparator and Comparable interfaces. 您的类(狗)同时实现ComparatorComparable接口。 We can say that Dog is a Comparator (with compare() implementation). 我们可以说Dog是一个Comparator (具有compare()实现)。

So it is okay to use it new Dog() as Comparator for sort() . 因此可以将new Dog()用作sort() Comparator器。 It will sort the elements using the logic you given in compare() . 它将使用您在compare()给定的逻辑对元素进行排序。

暂无
暂无

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

相关问题 什么可能导致Collections.sort(列表 <T> ,比较者 <? super T> )抛出ClassCastException? - What might cause Collections.sort(List<T>, Comparator<? super T>) to throw a ClassCastException? 与Collections.sort()一起使用的比较器,用于alphanumberic列表 - Comparator to be used with Collections.sort() for a alphanumberic list 制作比较器对象以对通用列表进行排序 <? extends T> 使用Collections.sort() - Crafting a Comparator object for sorting generic List<? extends T> using Collections.sort() 使用比较器DEBUG的collections.sort(list,比较器) - collections.sort(list, comparator) using comparator DEBUG Collections.sort(list) 和 list.sort(Comparator) 的区别 - Difference between Collections.sort(list) and list.sort(Comparator) 试图解决“方法 sort(List<T> , 比较器<? super T> ) 在类型 Collections 中不适用于参数&quot; - Trying to solve "The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments" 得到错误方法排序(列表<t> , 比较器<!--? super T--> ) Collections 类型不适用于 arguments</t> - Getting error The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments 为什么 Collections.binarySearch(List<? extends T> 列表、T 键、比较器<? super T> c) 方法需要一个 Comparator 对象作为它的参数? - Why does the Collections.binarySearch(List<? extends T> list, T key, Comparator<? super T> c) method require a Comparator object as it argument? Collections.sort 不适用于自定义比较器? - Collections.sort won't work with custom comparator? Collections.sort()声明:为什么<?超级T>而不是<T> - Collections.sort() declaration: why <? super T> rather than <T>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM