a- package treesetdemo;
- /**
- * 定义学生对象,其可进行年龄大小的比较,所以需要实现Comparable接口
- * */
- public class Student implements Comparable<Student>{
- private String name;
- private int age;
- public Student(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- //复写Comparable中的compareTo方法
- //返回正数则是自然升序 负数为 降序 0 则认为是是同一元素
- @Override
- public int compareTo(Student o) {
- // TODO Auto-generated method stub
- int result = this.age - o.age; //比较年龄大小
- if(result == 0){
- result = this.name.compareTo(o.name);//当年龄相同时,按姓名自然排序排
- }
- return result;
- }
-
-
- }
- package treesetdemo;
- import java.util.TreeSet;
- public class TreeSetDemo1 {
- /**
- * 需求:存储自定义的学生对象,并保证元素的唯一性,并按照年龄从小到大排序
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //建立TreeSet
- TreeSet<Student> ts = new TreeSet<Student>();
- //建立学生对象
- Student s1 = new Student("uiui",18);
- Student s2 = new Student("haha",22);
- Student s3 = new Student("gege",12);
- Student s4 = new Student("Lili",18);
- Student s5 = new Student("Licu",13);
- Student s6 = new Student("Lili",18);
- //添加对象
- ts.add(s1);
- ts.add(s2);
- ts.add(s3);
- ts.add(s4);
- ts.add(s5);
- ts.add(s6);
- //遍历集合
- for(Student s: ts){
- System.out.println(s.getName()+"..."+s.getAge());
- }
- }
- }
复制代码
|
|