等于具有可比接口的方法合同 [英] equals method contract with comparable interface

查看:115
本文介绍了等于具有可比接口的方法合同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有像Person这样的自定义类:

I have a custom class like Person:

public class Person {
    int age;
    String name;
}

现在我要排序基于年龄的类对象

所以我将使用 Comparable 接口和实现 compareTo()方法。

So I will use Comparable interface and implement compareTo() method.

compareTo 将有基于年龄比较人物对象的逻辑。

And compareTo will have logic to compare person object based on just age.

所以,如果我这样做的话:

So if I do :

Collections.sort(list);  // where list is a list of person

我将根据<$ c $获得排序人员列表c>年龄。

但我在某处读到,我们需要覆盖 equals()当我们做可比较实施时的方法。

But I read somewhere, we need to override equals() method as well when we do Comparable implementation.

但我现在没有看到它的使用。

But I am not seeing its use as of now.

任何人都可以解释,如果我想要的话,还需要覆盖 equals()方法 sort 基于年龄

Can anyone explain, where there will be a need to override equals() method as well if I want to just sort based on age?

推荐答案

没有法律涉及 Comparable.compareTo() equals()。但是我会说,如果 compaeTo()返回 0 等于( )返回 false

There is no law that relates Comparable.compareTo() and equals(). However I'd say that it is confusing if compaeTo() returns 0 while equals() returns false.

我认为在你的情况下你应该使用自定义比较器而不是使你的班级可比较。原因是今天你的比较标准是年龄,明天它将是人的名字,然后是姓氏,然后是体重......等等。这就是比较者介绍了应该使用的用例。

I think that in your case you should use custom comparator instead of making your class Comparable. The reason is that today your comparison criteria is age, tomorrow it will be the person's first name, then last name, then weight... etc, etc. This is the reason that Comparator was introduced and the use case when it should be used.

这篇关于等于具有可比接口的方法合同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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