posts - 4, comments - 0, trackbacks - 0, articles - 0

          用內部內實現的比較器

          Posted on 2007-08-20 00:50 追 .追..追.. 閱讀(196) 評論(0)  編輯  收藏
          import java.util.*;
          class TreeSetTest
          {
                 public static void main(String[] args)
                 {
                           TreeSet ts=new TreeSet(new Student.StudentCompare());
                           ts.add(new Student(22,"zhangsan"));
                           ts.add(new Student(25,"lisi"));
                            ts.add(new Student(22,"zhangan"));
                           ts.add(new Student(18,"wangwu"));
                           Iterator it=ts.iterator();
                           while(it.hasNext())
                           {
                                     System.out.println(it.next());
                           }
                 }
          }
          class Student
          {
                    int age;
                    String name;
                    static class StudentCompare implements Comparator 
                    {
                                 public int compare(Object o1,Object o2)
                                 {
                                           Student s1=(Student)o1;
                                           Student s2=(Student)o2;
                                            int result=s1.age>s2.age ? 1 : (s1.age == s2.age ? 0 : -1);
                                             if(result==0)
                                             {
                                                        result=s1.name.compareTo(s2.name);
                                              }
                                              return result;
                                  }
           
                    }
                    Student(int age,String name)
                    {
                                 this.age=age;
                                 this.name=name;
                    }
                    public String toString()
                    {
                                 return "age= "+age+","+"name= "+name;
                    }
          }

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 垫江县| 马龙县| 左贡县| 江口县| 胶南市| 旅游| 湖南省| 太康县| 广西| 阳城县| 张掖市| 黄骅市| 肥东县| 寻乌县| 柏乡县| 达拉特旗| 蛟河市| 西丰县| 绥芬河市| 荣成市| 兴城市| 连山| 鹤峰县| 根河市| 永寿县| 吉安县| 平凉市| 利津县| 昌都县| 洞头县| 临夏市| 泉州市| 连州市| 慈溪市| 卫辉市| 赣州市| 青冈县| 涟水县| 凉城县| 深州市| 宁蒗|