Comparable接口用于对象的比较,任何使用Comparable接口的类必须提供compareTo方法。这个方法返回一个整数代表两个对象差值。如果相比较的两个接口类型不可比,会抛出ClassCastException
compareTo应用例子
package inheritanceAndPolymorphism;
import java.util.*;
public abstract class Shape implements Comparable{
private String name;
//constructor
public Shape(String shapeName) {
name = shapeName;
}
public String getName() { //an abstract method can have both abstract and concrete method
return name;
}
public abstract double area();
public abstract double perimeter();
public double semiPerimeter() {
return perimeter() / 2;
}
public int compareTo(Object obj) {
final double EPSILON = 1.0e-15; //machine precision, in case of round-off error
Shape rhs = (Shape) obj;
double diff = area() - rhs.area();
if (Math.abs(diff) <= EPSILON * Math.abs(area())) {
return 0; //area of this shape equals area of obj
} else if (diff < 0) {
return -1; //area of this shape less than area of obj
} else {
return 1; //area of this shape greater than area of obj
}
}
/*
* The Circle Square, and other subclasses of Shape will automatically implement
* Comparable and inherit the compareTo method
*/
注意:
1对于小数的比较,要防止round-off error,因此判断是否相等不可直接等号,而是判断误差是否在计算机精度之内
2compareTo的第一步要把Object转化为该类类型(Shape),否则计算机将找不到方法Area()
下面例子在两个对象中找最大
package inheritanceAndPolymorphism;
public class FindMaxTest {
//return the larger of two objects a and b
public static Comparable max (Comparable a, Comparable b) {
if (a.compareTo(b) > 0) {
return a;
} else {
return b;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//test max on two Shape objects
Shape s1 = new Circle(3.0, "circle");
Shape s2 = new Square(6.5, "square");
System.out.println("Area of " + s1.getName() + " is " + s1.area());
System.out.println("Area of " + s2.getName() + " is " + s2.area());
Shape s3 = (Shape)max(s1, s2);
System.out.println("The larger shape is the " + s3.getName());
}
}
1本例中方法参数为Comparable类型,s1 s2均为Comparable因此不需要类型转换
2基础数据类型不是对象,不可使用Comparable