何时使用 Comparable 和 Comparator [英] When to use Comparable and Comparator

查看:30
本文介绍了何时使用 Comparable 和 Comparator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要在字段上排序的对象列表,例如 Score.我没有多想就写了一个实现 Comparator 的新类,它可以完成任务并且可以工作.

I have a list of objects I need to sort on a field, say Score. Without giving much thought I wrote a new class that implements Comparator, that does the task and it works.

现在回想起来,我想知道我是否应该让我的类实现 Comparable 而不是创建一个实现 Comparator 的新类.分数是唯一可以对对象进行排序的字段.

Now looking back at this, I am wondering if I should have instead have the my class implement Comparable instead of creating a new class that implements Comparator. The score is the only field that the objects will be ordered on.

  1. 我做了什么可以接受的做法?

  1. What I have done acceptable as a practice?

首先让类实现 Comparable(用于自然排序),如果需要替代字段比较,然后创建一个实现 Comparator 的新类"是否正确?

Is the right approach "First have the class implement Comparable (for the natural ordering) and if an alternative field comparison is required, then create a new class that implements Comparator" ?

如果上面的(2)是正确的,那么是否意味着只有在类实现了Comparable之后才应该实现Comparator?(假设我拥有原始类).

If (2) above is true, then does it mean that one should implement Comparator only after they have the class implement Comparable? (Assuming I own the original class).

推荐答案

我会说一个对象应该实现 Comparable 如果这是对类进行排序的清晰自然的方式,并且任何需要对类进行排序的人通常都希望这样做.

I would say that an object should implement Comparable if that is the clear natural way to sort the class, and anyone would need to sort the class would generally want to do it that way.

但是,如果排序是类的不寻常使用,或者排序仅对特定用例有意义,那么 Comparator 是更好的选择.

If, however, the sorting was an unusual use of the class, or the sorting only makes sense for a specific use case, then a Comparator is a better option.

换句话说,给定类名,是否清楚可比较的排序方式,还是必须求助于阅读 javadoc?如果是后者,很可能每个未来的排序用例都需要一个比较器,此时可比较的实现可能会减慢类的用户,而不是加快他们的速度.

Put another way, given the class name, is it clear how a comparable would sort, or do you have to resort to reading the javadoc? If it is the latter, odds are every future sorting use case would require a comparator, at which point the implementation of comparable may slow down users of the class, not speed them up.

这篇关于何时使用 Comparable 和 Comparator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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