利用Comparable接口实现Arrays.sort的重写

 想根据对象的某一类属性排序,为了代码的可读性,也想用学习c++时对operator的重载,实现排序功能


调用了Comparable接口(返回1表明比后者大,返回0表示和后者相等,返回-1表明比后者小)

系统已经定义好Comparable接口,内部有抽象方法

package T;
import java.util.*;

class Circle {
    double radius;

    Circle(double r){
        this.radius = r;
    }

    Circle() {
    }

    public double Get() {
        return radius;
    }

    public void Set(double radius) {
        this.radius = radius;
    }
    public double calculateArea(){
        return 3.14*radius*radius;
    }
}

//class Ellipse extends Circle{
//    double a;
//    double b;
//    Ellipse(double a, double b){
//        super(0);
//        this.a = a;
//        this.b = b;
//    }
//    public void Set(double a, double b) {
//        this.a = a;
//        this.b = b;
//    }
//    public double calculateArea(){
//        return 3.14*(a/2)*(b/2);
//    }
//}

class Cylinder extends Circle implements Comparable<Object>{
    double h;
    double area;
    Circle bottom;
    Cylinder(double r, double h){
        bottom = new Circle(r) ;
        this.h = h;
        area = 2*3.14*r*(h+r);
    }
    public double getH(){
        return h;
    }
    public double getR(){
        return bottom.Get();
    }
    public void setBottom(double r){
        bottom.Set(r);
        area = 2*3.14*r*(h+r);
    }
    public void setH(double h){
        this.h = h;
        area = 2*3.14*bottom.Get()*(h+bottom.Get());
    }

    public double calculateArea(){
        return area;
    }
    
    public int compareTo(Object o){
    	if(o instanceof Cylinder){
    		Cylinder c = (Cylinder) o;
    		if(this.area < c.calculateArea()){
    			return 1;
    		}else if(this.area == c.calculateArea()){
    			return 0;
    		}else{
    			return -1;
    		}
    	}
		return 0;
    }
}

public class Test {


	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Cylinder[] c = new Cylinder[5];
		c[0] = new Cylinder(2.0, 10.0);
		c[1] = new Cylinder(1.0, 10.0);
		c[2] = new Cylinder(4.0, 10.0);
		c[3] = new Cylinder(1.0, 10.0);
		c[4] = new Cylinder(9.0, 10.0);
		
//		for(int i = 0; i < 2; i ++){
//			for(int j = i+1; j < 3; j ++){
//				if(c[i].calculateArea() <= c[j].calculateArea()){
//					Cylinder t;
//					t = c[i];
//					c[i] = c[j];
//					c[j] = t;
//				}
//			}
//		}
		
		Arrays.sort(c);
		for(int i = 0; i < c.length; i ++){
			System.out.println("c[" + i + "]" + "的底面半径为:" + c[i].getR());
			System.out.println("  高为:" + c[i].getH());
			System.out.println("  面积为:" + c[i].calculateArea());
		}
	}

}

posted @ 2021-09-26 14:55  泥烟  阅读(29)  评论(0编辑  收藏  举报