当前位置:网站首页>集合-Set

集合-Set

2022-06-21 20:56:00 耳东哇

import java.util.Iterator;
import java.util.TreeSet;

public class note144 implements Comparable<Object> {
    
    String name;
    long id;

    public note144(String name, long id) {
    
        this.name = name;
        this.id = id;
    }

    public String getName() {
    
        return name;
    }

    public void setName(String name) {
    
        this.name = name;
    }

    public long getId() {
    
        return id;
    }

    public void setId(long id) {
    
        this.id = id;
    }

    public int compareTo(Object o) {
    //实现接口,比较此对象与指定对象的顺序
        note144 upstu = (note144) o;
        int result = id > upstu.id ? 1 : (id == upstu.id ? 0 : -1);
        return result;
    }

    public static void main(String[] args) {
    
        note144 stu1 = new note144("一一", 1011);
        note144 stu2 = new note144("二娃", 1022);
        note144 stu3 = new note144("三叔", 1033);
        TreeSet<note144> tree = new TreeSet<>();//创建集合
        tree.add(stu1);
        tree.add(stu2);
        tree.add(stu3);


        Iterator<note144> it = tree.iterator();//Set集合中的所有对象的迭代器(获取迭代器)
        while (it.hasNext()) {
    
            note144 stu = (note144) it.next();
            System.out.println(stu.getId() + ":" + stu.getName());
        }

        it = tree.headSet(stu2).iterator();//j截取排在stu2对象之前的对象
        System.out.println("截取前面部分的集合");
        while (it.hasNext()) {
    
            note144 stu = (note144) it.next();
            System.out.println(stu.getId() + stu.getName());
        }
        it = tree.subSet(stu2, stu3).iterator();
        System.out.println("截取中间部分的集合");
        while (it.hasNext()) {
    
            note144 stu = (note144) it.next();
            System.out.println(stu.getId() + stu.getName());
        }

    }
}

原网站

版权声明
本文为[耳东哇]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43930851/article/details/125158329