Comparable接口中的CompareTo方法
一个类若要实现Comparable接口,必须要override里面的compareTo方法
public class Circle implements Comparable<Circle>{
private double radius;
public Circle(){
}
public Circle(double radius){
this.radius = radius;
}
public double getPerimeter(){ //求周长方法
return 2*radius*Math.PI;
}
public double getArea(){ //求面积方法
return radius*radius*Math.PI;
}
@Override //要实现Comparable接口中的CompareTo方法
public int compareTo(Circle o) {
if(this.getArea() > o.getArea())
return 1;
else if(this.getArea()<o.getArea())
return -1;
else
return 0;
}
public static void main(String[] args){
//Circle circle = new Circle();
Circle[] circles = new Circle[]{
new Circle(3.4),new Circle(2.5),new Circle(5.8)
};
System.out.println(circles[0].compareTo(circles[1]));
System.out.println(circles[1].compareTo(circles[2]));
}
}
运行结果