对象的比较可以在 java 中使用接口 Comparable/Comparator 来完成。Comparable 接口用于指定对象的自然顺序,而比较器通常由程序员用于更改特定对象遵循的自然顺序并指定其排序偏好
在你的例子中
public class Test implements Comparable<Test> {
private final int a;
private final int b;
public static void main(String[] args) {
Test x1 = new Test(9999, 9999);
Test x2 = new Test(0, 0);
int comparisionVal = x1.compareTo(x2);
System.out.println(comparisionVal > 0 ? "First object is greater"
: (comparisionVal < 0 ? "Second object is greater"
: "both are equal"));
}
public Test() {
this.a = 0;
this.b = 0;
}
public Test(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Test o) {
return this.a - o.a; // ascending based on a
// return this.a - o.a; // descending based on a
}
@Override
public String toString() {
return "a = " + this.a + "; b = " + this.b;
}
}
Comparable 和comparator 通常用于排序。这可以在您的示例中进行说明,如下所示
public class Test implements Comparable<Test> {
private final int a;
private final int b;
public static void main(String[] args) {
Test x1 = new Test(9999, 9999);
Test x2 = new Test(0, 0);
Test x3 = new Test(4444, 4444);
Test x4 = new Test(555, 555);
List<Test> list = new ArrayList<Test>();
list.add(x1);
list.add(x2);
list.add(x3);
list.add(x4);
Collections.sort(list);
System.out.println("The object in ascending order: " + list);
// If you wish to do a descending sort that is where you'd use
// comparator
Collections.sort(list, new Comparator<Test>() {
@Override
public int compare(Test o1, Test o2) {
return o2.a - o1.a;
}
});
System.out.println("The object in descending order: " + list);
}
public Test() {
this.a = 0;
this.b = 0;
}
public Test(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Test o) {
return this.a - o.a; // ascending based on a
// return this.a - o.a; // descending based on a
}
@Override
public String toString() {
return "a = " + this.a + "; b = " + this.b;
}
}