关于Collections.sort的混淆(List <t> list,Comparator <! - ?super T - > c)示例

时间:2015-04-22 11:27:14

标签: java sorting collections generic-collections

这是代码

   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类型和Comparator类型的参数。但是当我们通过列表Dog和一个新的Dog of Dog时,我只是不明白compare()方法中发生了什么?即。

return d1.age - d2.age;

这意味着什么?如果我做了

return d1.age + d2.age; 

为什么会改变排序?

1 个答案:

答案 0 :(得分:3)

一个好的做法是使用compare方法编写此类Integer.compare()方法:

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

我认为,这种情况更加明显,这里发生了什么。 (另外,这种方式更安全。)