关于 Collections.sort(List<T> list, Comparator<? super T> c) 例子的困惑

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

这是代码

   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() + ", ");
    }
}

我知道这里的 2 参数排序方法采用 List 类型的参数和一个比较器。但是在这里当我们传递列表 Dog 和一个新的 Dog 对象时,我只是不明白 compare() 方法中发生了什么?即

return d1.age - d2.age;

这是什么意思?如果我这样做

return d1.age + d2.age; 

为什么会改变顺序?

对于d1.age - d2.age

  • 如果为负数,则按排序顺序 d1 在逻辑上小于 d2
  • 如果为正,则 d1 在排序顺序上逻辑上大于 d2
  • 如果为0,则对象相等

可以参考javadoc for compare method

因此,当您对狗进行分类时,您的比较方法是比较它们的年龄,因此 Tammy 小于 Lacy你的方法实现。

让 Dog 实现 ComparableComparator 对我来说似乎不是个好主意。

  • Collections.sort(list) 将导致 compareTo() 方法 调用
  • Collections.sort(list, new Dog()) 将导致调用 compare() 方法

我相信您应该研究使用 Comparable and Comparator

对用户定义的对象进行排序

一个好的做法是编写这样的 compare methods using Integer.compare() 方法:

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

我想,这样更明显,这里发生了什么。 (而且,这种方式更安全。)

您的 class(狗)实现了 ComparatorComparable 接口。 我们可以说 Dog 是一个比较器(具有 compare() 实现)。

所以可以将它 new Dog() 用作 Comparator 用于 sort()。它将使用您在 compare().

中给出的逻辑对元素进行排序