對象的比較可以在Java中使用任何接口可比/比較器來完成。 可比接口用於指定對象的自然順序,而比較普遍使用的程序員改變自然順序其次是特定的對象,並指定他的排序偏好
在您的例子
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;
}
}
比較和比較器通常用於排序。這可以在例如被示出爲下面
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;
}
}
實現接口'Comparable':設置以及一個示例:http://docs.oracle.com/javase/6/docs/ api/java/lang/Comparable.html – home
您想如何比較這些對象?哪一個對象會更大?a = new Test(1,2)'或'b = new Test(2,1)'? – Pshemo
要比較哪些屬性? – xyz