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

用内部内实现的比较器

Posted on 2007-08-20 00:50 追 .追..追.. 阅读(172) 评论(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;
          }
}

只有注册用户登录后才能发表评论。


网站导航: