- /*
- 这是关于TreeSet的功能演示.
- 需求:向TreeSet集合存入Student学生对象,并按照年龄进行排序
- */
- import java.util.*;
- class Student implements Comparable //创建学生类并实现Comparable类
- {
- private String name;
- private int age;
- Student(String name,int age) //构造函数初始化
- {
- this.name=name;
- this.age=age;
- }
- public String getName() //定义获取姓名的函数
- {
- return this.name;
- }
- public int getAge() //定义获取年龄的函数
- {
- return this.age;
- }
- public void setName(String name) //定义改变姓名的函数
- {
- this.name=name;
- }
- public void setAge(int age) //定义改变年龄的函数
- {
- this.age=age;
- }
- public int compareTo(Object obj) //复写compareTo方法
- {
- if(!(obj instanceof Student))
- throw new RuntimeException(); //抛出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 TreeSetDemo
- {
- public static void main(String[] args)
- {
- TreeSet ts=new TreeSet(); //创建容器
- ts.add(new Student("xiaochen01",31));
- ts.add(new Student("xiaochen01",31));
- ts.add(new Student("xiaochen02",32));
- ts.add(new Student("xiaochen03",33));
- ts.add(new Student("xiaochen04",34));
- ts.add(new Student("xiaochen05",30));
- ts.add(new Student("xiaochen06",30));
-
- Iterator it=ts.iterator(); //获取迭代器
- //遍历并输出容器中的数据
- while(it.hasNext())
- {
- Student s=(Student)it.next();
- sop(s.getName()+"......"+s.getAge());
- }
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码 问题1:为什么要实现Coparrable类呢?现在自己写的compareTo方法已经可以比较两个数的大小了
问题2:
运行结果如下: 为什么xiaochen04进来之后不用跟xiaochen01比较大小呢?
xiaochen01...compareTO...xiaochen01
xiaochen02...compareTO...xiaochen01
xiaochen03...compareTO...xiaochen01
xiaochen03...compareTO...xiaochen02
xiaochen04...compareTO...xiaochen02
xiaochen04...compareTO...xiaochen03
xiaochen05...compareTO...xiaochen02
xiaochen05...compareTO...xiaochen01
xiaochen06...compareTO...xiaochen02
xiaochen06...compareTO...xiaochen01
xiaochen06...compareTO...xiaochen05
xiaochen05......30
xiaochen06......30
xiaochen01......31
xiaochen02......32
xiaochen03......33
xiaochen04......34
|