// 類的自定義比較
class Dog implements Comparable<Dog> {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// 看你自己默認(rèn)排序哪一個
@Override
public int compareTo(Dog o) {
return this.age - o.age; //調(diào)用Arrays.sort() 默認(rèn)排序狗的年齡 從小到大排序
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Comparator(外部比較器)
// 想弄實例化的排序就要調(diào)用Comparator
class ReverSortDogName implements Comparator<Dog> {
@Override
public int compare(Dog o1, Dog o2) {
return o2.getName().compareTo(o1.getName());
}
}
執(zhí)行
import java.util.Arrays;
import java.util.Comparator;
public class 簡書 {
public static void main(String[] args) {
Dog[] dogs = new Dog[]{new Dog("歐富華", 23), new Dog("xie", 18), new Dog("哈哈", 12)};
// Arrays.sort(dogs);Comparable 但指,執(zhí)行這個方法默認(rèn)是按age從小到大排序
// Arrays.sort(dogs, new ReverSortDogName()); Comparator,按name字符串編碼從大到小排序
System.out.println(Arrays.toString(dogs));
}
}