java对象比较规则:Comparable & Comparator

两个接口都是用来定义比较规则的
Comparable接口(用于在类内部定义比较规则,一个类只能定义一个)

public int compareTo(Dog o)

Comparator接口(在类外部定义比较规则,可以定义多个比较规则使用)

public int compare(Dog o1, Dog o2)

使用:
在一些排序的应用中将使用接口
比如:TreeSet和TreeMap

java.util.TreeSet.TreeSet<Dog>(Comparator<? super Dog> comparator)

TreeSet可以创建有序的集合,此时将使用到排序规则,上述使用的Dog对象要么实现comparable接口,
要么在创建TreeSet实例时传入Comparator作为比较规则使用
如果两者都没有,报错。
如果两者都有,将使用传入的Comparator对象作为比较规则

TreeMap的put方法:

public V put(K key, V value) {
        ....
        ....
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;

        //在这里开始判断,if 传入了Comparator对象,则使用这个对象的比较规则
        //else 调用对象的Comparable.compareTo方法,
        //如果对象没有实现Comparable接口,则不能强转成功,抛出异常
        if (cpr != null) {
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        else {
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
                Comparable<? super K> k = (Comparable<? super K>) key;
            do {
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
    }   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值