微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

 

 

结果:

taoshihan2===20

taoshihan1===30

taoshihan3===40

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐