利用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());
}
}
}
本文来自博客园,作者:泥烟,CSDN同名, 转载请注明原文链接:https://www.cnblogs.com/Knight02/p/15799091.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY