java比较器,如何按整数排序?

2022-08-31 21:07:13

我试图学习Java中的比较器,我在网上找到了这个很好的例子,我的问题是如何更改此代码,以便按年龄和降序排列宠物名称,以便最老是第一个,最年轻的是最后一个?

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

答案 1

简单更改

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

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

如果这是您要寻找的,则应按相反的年龄顺序对它们进行排序。

更新:

@Arian在他的评论中是正确的,那么为狗声明比较器的公认方法之一就是将其声明为类本身的公共静态最终字段。

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

    public static final Comparator<Dog> DESCENDING_COMPARATOR = new Comparator<Dog>() {
        // Overriding the compare method to sort the age
        public int compare(Dog d, Dog d1) {
            return d.age - d1.age;
        }
    };

    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);
    }

}

然后,您可以在代码中要比较狗的任何地方使用它,如下所示:

// Sorts the array list using comparator
Collections.sort(list, Dog.DESCENDING_COMPARATOR);

实现Ableable时要记住的另一件重要事情是,compareTo与equals一致地执行是很重要的。尽管不是必需的,但如果不这样做,可能会导致某些集合(如 Set 的某些实现)出现奇怪的行为。有关实现 compareTo 的合理原则的更多信息,请参阅文。

更新 2:Chris 是对的,此代码容易溢出,因为年龄的大负值。在Java 7及更高版本中实现此目的的正确方法是代替。Integer.compare(d.age, d1.age)d.age - d1.age

更新 3:使用Java 8,您的比较器可以更简洁地编写为:

public static final Comparator<Dog> DESCENDING_COMPARATOR = 
    Comparator.comparing(Dog::getDogAge).reversed();

的语法保持不变,但可以写为Collections.sortcompare

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

答案 2
public class DogAgeComparator implements Comparator<Dog> {
    public int compare(Dog o1, Dog o2) {
        return Integer.compare(o1.getAge(), o2.getId());
    }
}

推荐