(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); } } }
原文地址:http://9808040.blog.51cto.com/9798040/1598629