TreeSet

TreeSet中的元素不可重复,可自动排序。

TreeSet<Integer> treeset = new TreeSet<>();//构建TreeSet

 排序功能演示

复制代码
public class Main {
    public static void main(String args[]) { 
        TreeSet<Integer> treeset = new TreeSet<>();
        treeset.add(12);
        treeset.add(13);
        treeset.add(1);
        treeset.add(0);
treeset.add(0);//测试TreeSet的元素可重复性 treeset.add(
15); Iterator<Integer> it = treeset.iterator(); while(it.hasNext()){ Integer next = it.next(); } for (Integer i:treeset) { System.out.println(i); } } }
输出:
0
1
12
13
15
//输出结果只有一个0
复制代码

需要注意的是,TreeSet对自定义类型不能进行排序、

复制代码
class Stu{
    int age ;
    public Stu(int age) {
        this.age = age;
    }
    
}
public class Main {
    public static void main(String args[]) { 
        TreeSet<Stu> trees = new TreeSet<>();
        Stu s1 = new Stu(1);
        Stu s2 = new Stu(2);
        Stu s3 = new Stu(45);
        trees.add(s1);
        trees.add(s2);
        trees.add(s3);

        for (Stu i:trees) {
            System.out.println(i);
        }

    }
}
运行以上代码后出现报错:Stream.Stu cannot be cast to java
复制代码

此时,我们需要为自定义类实现比较接口Comparable,代码示例:

复制代码
class Stu implements  Comparable<Stu>{
    int age ;
    public Stu(int age) {
        this.age = age;
    }
    @Override
    public int compareTo(Stu o) {
        if(this.age>o.age) {
            return 1;
        }else if(this.age<o.age) {
            return -1;
        }
        // TODO Auto-generated method stub
        return 0;
    }
    @Override
    public String toString() {
        return "Stu [age=" + age + "]";
    }
    
}
public class Main {
    public static void main(String args[]) { 
        TreeSet<Stu> trees = new TreeSet<>();
        Stu s1 = new Stu(1);
        Stu s2 = new Stu(100);
        Stu s3 = new Stu(50);
        trees.add(s1);
        trees.add(s2);
        trees.add(s3);

        for (Stu i:trees) {
            System.out.println(i);
        }

    }
}
输出:
Stu [age=1]
Stu [age=50]
Stu [age=100]


复制代码

总结:对于自定义的类型,想要在TreeSet中实现排序,必须实现Comparable接口或者编写Comparator比较器,制定其比较规则!JDK自己提供的数据类型不用程序员实现Comparable接口或者编写Comparator比较器是因为它的底层源码都实现了Comparable接口,具有了比较规则,故可以排序!所以在对自定义类构建TreeSet时要注意自行编写比较方法

 

posted @   kandhera  阅读(37)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示