Java 8:实现可比性 [英] Java 8: implementing Comparable

查看:71
本文介绍了Java 8:实现可比性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢Comparator的新静态工厂方法,因为它们允许以非常简洁且不易出错的方式实现Comparators.

I like the new static factory methods of Comparator, as they allow to implement Comparators in a very concise and less error-prone way.

但是实现Comparable的推荐方法是什么?我们应该在Comparable实现中使用Comparators吗?

But what is the recommended way to implement Comparable? Should we use Comparators inside the Comparable implementation?

public MyClass implements Comparable<MyClass>{
...
    public int compareTo(MyClass other){
        Comparator<MyClass> naturalOrderComparator = 
            Comparator.comparing(MyClass::getFoo)
                      .thenComparing(MyClass::getBar);
        return naturalOrderComparator.compare(this, other);
    } 
}

甚至在对庞大的集合进行排序时甚至使用静态比较器来减少大量对象的创建:

or even use a static comparator to reduce a lot of object creation when sorting huge collections:

public MyClass implements Comparable<MyClass>{
    private static final Comparator<MyClass> NATURAL_ORDER_COMPARATOR =     
        Comparator.comparing(MyClass::getFoo)
                  .thenComparing(MyClass::getBar);

    ...

    public int compareTo(MyClass other){
        return NATURAL_ORDER_COMPARATOR.compare(this, other);
    } 
}

或者是否存在另一种推荐的方法来实现与Java SE 8的可比性?

Or is there another recommended way to implement Comparable with Java SE 8?

推荐答案

您自己的选择2几乎可以肯定是目前可用的最佳方法.它避免分配,读取效果很好-尤其是将静态常量放在compareTo方法旁边.

Your own Option 2 is almost certainly the best currently available way. It avoids allocation, it reads pretty well -- especially if you put the static constant next to the compareTo method.

Java 8中新的Comparator.comparing工厂方法非常易于阅读,甚至更好,更难以搞定-有很多很多方法来手工错误地编写比较,这比我想记住的要多,而且工厂方法不受大多数​​方法的影响.尽管使用它们编写compareTo方法而不是Comparator对象有点奇怪,但它仍然比替代方法要好.

The new Comparator.comparing factory methods in Java 8 are very easy to read, and even better, difficult to screw up -- there are many, many ways to write comparisons incorrectly by hand, more than I care to remember, and the factory methods are immune to most of them. Even though it's a little weird to use them to write a compareTo method instead of a Comparator object, it's still better than the alternatives.

这篇关于Java 8:实现可比性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆