向treeset中放入元素

public class TreeSetTest {

    @Test
    public void test1() {
        // treeset中放入的元素要能够排序
        Set set = new TreeSet();
        set.add(1);
        set.add(2);
        set.add(3);

        // treeset中只能放入同一种元素
        // string类也实现了comparable接口,但是不能放入
        //set.add("a");

        // treeset中放入其它对象
        // 1. 该对象实现comparable接口
        Set set2 = new TreeSet();
        set2.add(new Clazz1("a",99));
        set2.add(new Clazz1("b",96));
        System.out.println(set2); // [Clazz1{name='b', score=96}, Clazz1{name='a', score=99}]

        // 2. 自定义排序
        Set set3 = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) { // compare 方法:o1 > 02 返回正整数
                // 我现在写的o2-o1
                return ((Clazz1)o2).score - ((Clazz1)o1).score;
            }
        });
        set3.add(new Clazz1("a",99));
        set3.add(new Clazz1("b",96));
        set3.add(new Clazz1("c",96)); // 去重了
        // [Clazz1{name='a', score=99}, Clazz1{name='b', score=96}]
        System.out.println(set3);

        // 怎么不让treeset去重呢?
        // treeset去重是因为,两个对象比较的结果为0
        Set set4 = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                int s1 = ((Clazz1) o2).score;
                int s2 = ((Clazz1) o1).score;
                if (s1-s2 == 0){
                    //return 1.1; // 必须返回一个整数,表示o1 大于 o2
                    return 1;//返回一个正整数,表示o1 大于 o2
                }
                return s1-s2;
            }
        });
        set4.add(new Clazz1("a",99));
        set4.add(new Clazz1("b",96));
        set4.add(new Clazz1("c",96));
        // 这次就没有去重
        System.out.println(set4);
    }
}
class Clazz1 implements Comparable{
    String name;
    int score;

    @Override
    public String toString() {
        return "Clazz1{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }

    public Clazz1(String name, int score) {
        this.name = name;
        this.score = score;
    }

    @Override
    public int compareTo(Object o) {
        // 用ojbect接受一个Clazz1变量,需要造型
        return this.score-((Clazz1) o).score;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值