您的位置:首页 > 编程语言 > Java开发

Java中对象比较和排序实例

2015-01-03 11:03 399 查看
(1)对Element对象进行排序(根据体重和年龄)
(2)要想使用Arrays.sort支持排序的类必须实现Comparable接口

public class Elephant  implements  Comparable {

int weight ;
int   age    ;
float tusklength;
@Override
public int compareTo(Object o) {

Elephant  otherelephant =(Elephant) o;
if(this.weight>otherelephant.weight){
return 1 ;
}
else if(this.weight
return -1;
}
else {
return (this.age-otherelephant.age);
}
}

/*
* 根据Elephant类写的一个测试类对Elephant对象根据体重和年龄进行排序
* */
import java.util.Arrays;
public class ElephantTest {
public static void main(String[] args) {
Elephant elephant1 =new Elephant();
elephant1.weight=1000;
elephant1.age   =10;
Elephant elephant2=new Elephant();
elephant2.weight=200;
elephant2.age   =200;

Elephant elephant3=new Elephant();
elephant3.weight=300;
elephant3.age   =30 ;

Elephant[] elephants =new Elephant[3];
elephants[0]=elephant1;
elephants[1]=elephant2;
elephants[2]=elephant3;
System.out.println("排序前!");
for(Elephant  elephant:elephants){
System.out.println("体重"+elephant.weight+":"+"年龄"+elephant.age);
}
Arrays.sort(elephants);
System.out.println("排序后:");
for(Elephant elephant:elephants){
System.out.println("体重"+elephant.weight+":"+"年龄"+elephant.age);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Comparable compareTo