TreeSet存储自定义对象并保证排序和唯一

本文介绍如何使用Java中的TreeSet存储自定义对象,并确保这些对象能根据指定规则进行排序和保持唯一性。通过实现Comparable接口,我们定义了学生对象的比较规则,首先按年龄排序,若年龄相同则按姓名进行区分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TreeSet存储自定义对象并保证排序和唯一

/*

    如果一个类的元素要想能够进行自然排序,就必须实现自然排序接口

 */

public classStudent implementsComparable<Student>{

 

    private String name;

    private int age;

   

    public Student() {

        super();

        // TODO Auto-generated constructor stub

    }

   

    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;

    }

 

    @Override

    public int compareTo(Student s) {

        // TODO Auto-generated method stub

//      return-1;

        //这里返回什么,其实应该根据我的排序规则来做

        //按照年龄排序,主要条件

        int num = this.age - s.age;

        //次要条件

        //年龄相同的时候,还的看姓名是否也相同

        //如果年龄和姓名都相同,才是同一个元素

        int num2 = num ==0 ? this.name.compareTo(s.name) : num;

        return num2;

    }

 

}

 

import java.util.TreeSet;

 

/*

    TreeSet存储自定义对象并保证排序和唯一

    A:你没有告诉我们怎样排序

        自然排序,按照从小到大

    B:元素什么情况算唯一你也没有告诉我

        成员变量都相同即为同一个元素

 */

public classTreeSetDemo2 {

 

    public static void main(String[] args) {

        // TODO Auto-generated method stub

 

        //创建集合对象

        TreeSet<Student>ts = newTreeSet<Student>();

       

        //创建元素

        Students1 = newStudent("linqingxia",27);

        Students2 = newStudent("linqingxia2",28);

        Students3 = newStudent("linqingxia3",29);

        Students4 = newStudent("linqingxia4",26);

        Students5 = newStudent("linqingxia5",25);

        Students6 = newStudent("linqingxia",27);

        Students7 = new Student("linqingxia46",26);

       

        //天假元素

        ts.add(s1);

        ts.add(s2);

        ts.add(s3);

        ts.add(s4);

        ts.add(s5);

        ts.add(s6);

        ts.add(s7);

       

        //遍历

        for(Student s : ts){

            System.out.println(s.getName()+"---"+s.getAge());

        }

    }

 

}

 

运行结果:

linqingxia5---25

linqingxia4---26

linqingxia46---26

linqingxia---27

linqingxia2---28

linqingxia3---29

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值