点击运行
import java.util.*; class Dog implements Comparator
, Comparable
{ 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; } // 重写 compareTo 方法 public int compareTo(Dog d) { return (this.name).compareTo(d.name); } // 重写 compare 方法对 age 进行排序 public int compare(Dog d, Dog d1) { return d.age - d1.age; } } public class Example { public static void main(String args[]) { // 获取 Dog 对象列表 List
list = new ArrayList
(); 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) // 打印 name 的排序列表 System.out.print(a.getDogName() + ", "); // 使用比较器对数组列表进行排序 Collections.sort(list, new Dog()); System.out.println(" "); for(Dog a: list) // 打印 age 的排序列表 System.out.print(a.getDogName() +" : "+ a.getDogAge() + ", "); } }
运行结果 :
正在执行...