[javaSE] 集合框架(TreeSet)

TreeSet:可以对Set集合中的元素排序,默认按照ascii表排序,二叉树结构

左边叉是小的,右边叉是大的

 

存储自定义对象

定义一个类Student实现Comparable类,使自定义类具备比较性

定义属性年龄age

定义属性姓名name

实现compareTo()方法,传递进来另一个Student对象

判断当前Student对象的age大于另一个Student对象的age,返回1,否则返回-1

 

获取Student对对象

调用TreeSet对象的add()方法,参数:Student对象

遍历集合

复制代码
import java.util.TreeSet;


public class TreeSetDemo {


    /**
     * @param args
     */
    public static void main(String[] args) {
        TreeSet<Student> treeset=new TreeSet<Student>();
        treeset.add(new Student("taoshihan1",30));
        treeset.add(new Student("taoshihan2",20));
        treeset.add(new Student("taoshihan3",40));
        for(Student student:treeset){
            System.out.println(student.name+"==="+student.age);
        }
        
        
        
    }

}
class Student implements Comparable<Student>{
    
    public int age;
    public String name;
    public Student(String name,int age) {
        this.name=name;
        this.age=age;
    }
    @Override
    public int compareTo(Student o) {
        if(o.age<this.age){
            return 1;
        }else{
            return -1;
        }
    }
    
}
复制代码

 

 

结果:

taoshihan2===20

taoshihan1===30

taoshihan3===40

 

posted @   唯一客服系统开发笔记  阅读(292)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示
1
chat with us