阅读背景:

compareTo 方法的使用

来源:互联网 
                import java.util.*;public class UseComparator {  public static void main(String[] args) {  List list=new ArrayList();//数组列表  list.add(new Person(" 张三",56,1.75));//添加Person类对象到列表中  list.add(new Person("李四",26,1.83));  list.add(new Person("王五",46,1.65));  System.out.println("排序前列表中的元素:/n"+list);  Comparator comp=new HeightComparator();//创建比较器的对象  Collections.sort(list,comp);//根据比较器comp对列表对象排序  System.out.println("按身高排序后:/n"+list.toString());   }  //自定义比较器:   public static class HeightComparator implements Comparator  {   int heightCompare;//按身高比较时返回负整数、0或正整数,以确定大小   Person p1,p2;//比较器要比较的两个Person对象   public int compare(Object obj1,Object obj2)//实现接口中的方法   {    p1=(Person)obj1;    p2=(Person)obj2;    //比较两个对象的height大小:将他们包装为Double对象后比较    heightCompare=new Double(p1.height).compareTo(new Double(p2.height));    return heightCompare;//返回表示两个对象大小的标志,正数表示前一个大   }  }        }public class Person {String name;int age;double height;Person(String name,int age,double height){ this.name=name; this.age=age; this.height=height;}public String toString(){return name+":"+age+"岁,"+height+"米  "; }}                 import java.util.*;public class U



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: