treeset类

树集 treeset是将输入的元素自然排序后存储,最后输出的顺序也是自然排序后的顺序

同时,元素不可重复;

import java.util.TreeSet;

public class treeset {
    public static void main(String[] args) {
        //存储整数
        TreeSet<Integer> ts = new TreeSet<>();  //此时必须用Integer类
        ts.add(1);//会自动装箱
        ts.add(2);
        ts.add(-12);

        for (Integer i :ts){
            System.out.println(i); //会根据自然排序输出,且是不重复的
             //  -12  1 2
        }
    }
}

 

实现compare接口后存储

public class Student implements Comparable<Student> {
    String name ;
    int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override  // 重写compareto方法
    public int compareTo(Student c){
        /*return 0; //返回0 按照全部相同处理,返回 1 按照添加顺序
                  // 返回 -1 按照添加的逆序*/
        int num = this.age - c.age ;//其中this是后一个输入的,c指代前一个输出的
       int num2 = num ==0 ? this.name.compareTo(c.name) :num; //年龄相同的时候比较姓名
        //注意,this.name 是一个字符串,因为comparator接口实现了String,所以可以直接调用它的方法;
        return num2;

    }
}
import java.util.TreeSet;

public class treeset {
    public static void main(String[] args) {
        //存储整数
        TreeSet<Student> ts = new TreeSet<>();  //此时必须用Integer类
        ts.add(new Student("a",10));//会自动装箱
        ts.add(new Student("ab",12));
        ts.add(new Student("abc",13));

        for (Student i :ts){
            System.out.println(i.getName()+i.getAge()); //会根据自然排序输出,且是不重复的
        //由于排序规则里面返回值是0,故所有添加的元素最后在比较是都当成0,成为重复元素
       //最后只能添加一个元素
        }
    }
}

比较器comparator的使用:

public class treeset {
    public static void main(String[] args) {
        //带参构造,传递的参数是一个比较器接口,以内部类的形式写入,并重写了compare方法
        TreeSet<Student> ts = new TreeSet<>(
                new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num = o1.getAge()- o2.getAge();
                int num2 = num ==0 ? o1.getName().compareTo(o2.getName()):num;
                return num2;
            }
        });  //此时必须用Integer类
        ts.add(new Student("a",10));//会自动装箱
        ts.add(new Student("ab",12));
        ts.add(new Student("abc",13));

        for (Student i :ts){
            System.out.println(i.getName()+i.getAge()); //会根据自然排序输出,且是不重复的
        }
    }
}

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zero _s

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值