[javaSE] 集合框架(TreeSet)

前端之家收集整理的这篇文章主要介绍了[javaSE] 集合框架(TreeSet)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

 

存储自定义对象

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

定义属性年龄@H_403_3@age

定义属性姓名@H_403_3@name

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

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

 

获取@H_403_3@Student对对象

调用@H_403_3@TreeSet对象的@H_403_3@add()方法,参数:@H_403_3@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

 

猜你在找的Java SE相关文章