オブジェクトの比較は、インターフェイス Comparable/Comparator のいずれかを使用して Java で行うことができます。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;
}
}