黑马程序员技术交流社区

标题: TreeSet的两种排序方式 [打印本页]

作者: 和鹏    时间: 2015-4-13 14:18
标题: TreeSet的两种排序方式
/*
TreeSet的两种排序方式。
需求:让学生按照姓名排序。
*/

import java.util.*;
class TreeSetTest2
{
        public static void main(String[] args)
        {
                TreeSet ts = new TreeSet(new MyComparator());
                Student stu1 = new Student("张静01",22);
                Student stu2 = new Student("张静06",16);
                Student stu3 = new Student("张静02",21);
                Student stu4 = new Student("张静07",23);
                Student stu5 = new Student("张静01",20);
                Student stu6 = new Student("张静10",20);
                ts.add(stu1);
                ts.add(stu2);
                ts.add(stu3);
                ts.add(stu4);
                ts.add(stu5);
                ts.add(stu6);
                for (Iterator it = ts.iterator();it.hasNext(); )
                {
                        Student stu = (Student)it.next();
                        System.out.println(stu.getName()+"*****"+stu.getAge());
                }
        }
}
/**
*Student类实现Comparable接口
*/
class Student implements Comparable
{
        private String name;
        private int age;
        Student(String name,int age)
        {
                this.name = name;
                this.age = age;
        }
        public String getName()
        {
                return name;
        }
        public int getAge()
        {
                return age;
        }
        /**
        *复写Comparable接口的compareTo方法,对年龄进行比较
        */
        public int compareTo(Object obj)
        {
                if (!(obj instanceof Student))
                {
                                throw new RuntimeException("存入的对象不是学生!");
                }
                Student s = (Student)obj;
                System.out.println(this.name+"***compareTo***"+s.name);
                if (this.age>s.age)
                {
                        return 1;
                }
                if (this.age==s.age)
                {
                        return this.name.compareTo(s.name);
                }
                return -1;
        }
}
/**
*创造一个比较器
*/
class MyComparator implements Comparator
{
        /**
        *复写compare方法
        */
        public int compare(Object o1,Object o2)
        {
                Student stu1 = (Student)o1;
                Student stu2 = (Student)o2;
                int num = stu1.getName().compareTo(stu2.getName());
                if(num==0)
                {
                        return new Integer(stu1.getAge()).compareTo(new Integer(stu2.getAge()));
                }

                return num;
        }

}





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