不好的做法 - 类定义 compareTo(...) 并使用 Object.equals() [英] Bad practice - Class defines compareTo(...) and uses Object.equals()

查看:49
本文介绍了不好的做法 - 类定义 compareTo(...) 并使用 Object.equals()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道列出的方法需要做什么

Wondering what needs to be done for listed method

 public final int compareTo(final FieldDTO o) {
        return o.available.compareTo(this.available);

它在第 2 行抛出异常说明不好的做法 - 类定义 compareTo(...) 并使用 Object.equals() 16 天
field 定义 compareTo(FieldDTO) 并使用 Object.equals()

its throwing exception on line 2 stating Bad practice - Class defines compareTo(...) and uses Object.equals() 16 days
field defines compareTo(FieldDTO) and uses Object.equals()

不知道我应该如何处理.提前致谢.

Not sure how should i handle this. Thanks in advance.

推荐答案

如果你定义 compareTo 你至少应该定义 equals

If you define compareTo you should at least define equals

boolean equals(it) { 
  return compareTo(it) == 0; 
} 

否则当你把你的对象放在 Maps 和 Sets 时你会遇到奇怪的问题.通常也定义 hashCode 是一种好习惯.

otherwise you will get strange problems when you put your object in Maps and Sets. It is generally good practice to also define hashCode.

这篇关于不好的做法 - 类定义 compareTo(...) 并使用 Object.equals()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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