Java 自定义对象不能直接进行比较,需要实现 Comparable 接口或者 Comparator 接口。
1、Comparable 接口
此接口强行对实现它的每个类的对象自进行整体排序。这种排序被称为类的自然排序,类的compareTo 方法被称为它的自然比较方法。
package com.latiny.basic; import java.util.Arrays; public class ComparableTest { public static void main(String[] args) { int[] nums = {4, 3, 2, 1, 5, 6}; Arrays.sort(nums); System.out.println(Arrays.toString(nums)); String[] strs = {"Jack", "Rose", "Mia", "Latiny", "贝贝", "欢欢"}; Arrays.sort(strs); System.out.println(Arrays.toString(strs)); Bird[] cats = {new Bird("Jmy", 4), new Bird("Feign", 1), new Bird("Selina", 9)}; Arrays.sort(cats); System.out.println(Arrays.toString(cats)); } } class Bird implements Comparable<Bird> { String name; int age; public Bird() { super(); } public Bird(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "[name:" + name + ", " + "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; } @Override public int compareTo(Bird bird) { return this.age - bird.age; } }
2、Comparator
Comparator 接口是要求自定类去实现,按照OO原则,对修改关闭,对扩展开放。适合类已定义好,不能或者不想再去修改它时,又需要对它进行比较时,通过组合一个新类实现Comparator接口的 compare方法。
public class ComparableTest { public static void main(String[] args) { Bike[] bikes = {new Bike("Latiny", 20), new Bike("Luise", 30), new Bike("Jordan", 28)}; Arrays.sort(bikes, new BikeComparator()); System.out.println(Arrays.toString(bikes)); } } class BikeComparator implements Comparator<Bike> { @Override public int compare(Bike o1, Bike o2) { return o1.getSpeed() - o2.getSpeed(); } } class Bike { private String name; private int speed; public Bike(String name, int speed) { super(); this.name = name; this.speed = speed; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } @Override public String toString() { return "Bike [name=" + name + ", speed=" + speed + "]"; } }