黑马程序员技术交流社区

标题: TreeSet比较器实现 [打印本页]

作者: jk7130866    时间: 2015-7-29 19:42
标题: TreeSet比较器实现
class TreeDemo
{
        public static void main(String[] args)
        {
                TreeSet ts=new TreeSet(new MyCompare());
                ts.add(new Student("lisi",12));
                ts.add(new Student("lisi",13));
                ts.add(new Student("lis4",12));
                for(Iterator it=ts.iterator();it.hasNext();){
                        Student st=(Student)it.next();
                        System.out.println(st.getName());
                }
        }
}
class Student
{
        private String name;
        private  int age;
        public Student(String name,int age){
                this.name=name;
                this.age=age;
        }
        public String getName(){
                return name;
        }
        public int getAge(){
                return age;
        }
}
class MyCompare implements Comparator
{
        public int compare(Object o1,Object o2)
        {
                if(!(o1 instanceof Student&&o2 instanceof Student)){
                                throw new RuntimeException("yixhang ");}
                Student s1,s2;
                s1=(Student)o1;
                s2=(Student)o2;
                int num= s1.getName().compareTo(s2.getName());
                if (num==0)
                {
                        return s1.getAge()-s2.getAge();
                }
                return num;
               
        }
}
student类实现comparable接口省略了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2