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

          用內部內實現的比較器

          Posted on 2007-08-20 00:50 追 .追..追.. 閱讀(193) 評論(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;
                    }
          }

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


          網站導航:
           
          主站蜘蛛池模板: 加查县| 五莲县| 云梦县| 博乐市| 太和县| 郸城县| 广南县| 门源| 南华县| 新河县| 西藏| 桑植县| 广南县| 晴隆县| 棋牌| 盘锦市| 南陵县| 舟山市| 绥芬河市| 九江市| 牙克石市| 冀州市| 绥江县| 浏阳市| 庐江县| 清水县| 广元市| 鄂伦春自治旗| 当雄县| 宿迁市| 禄丰县| 依安县| 吉隆县| 桦川县| 安化县| 凤山市| 桂东县| 巫溪县| 舟曲县| 奉化市| 慈溪市|