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;
                    }
          }

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


          網站導航:
           
          主站蜘蛛池模板: 名山县| 昂仁县| 东城区| 大丰市| 大庆市| 田林县| 武威市| 塘沽区| 获嘉县| 随州市| 洛南县| 甘德县| 大港区| 中宁县| 城固县| 隆安县| 北碚区| 青阳县| 盖州市| 女性| 武山县| 个旧市| 永泰县| 富平县| 贵溪市| 铜川市| 灌南县| 镇康县| 迁安市| 丹棱县| 河间市| 佛坪县| 甘南县| 宜城市| 加查县| 昌都县| 富平县| 富蕴县| 克拉玛依市| 舞阳县| 隆安县|