Java中对象比较和排序实例
Java中对象比较和排序实例
Java中对象比较和排序实例
(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);
}
}
}
Java中介者设计模式
Java 设计模式之模板方法开发中应用
设计模式之 Java 中的单例模式(Singleton)
Java对象序列化
大话设计模式(带目录完整版) PDF+源代码
本文永久更新链接地址:
评论暂时关闭