用户登录
用户注册

分享至

不好的做法 - 类定义 compareTo(...) 并使用 Object.equals()

  • 作者: 夕阳下奔跑的姨妈
  • 来源: 51数据库
  • 2022-11-01

问题描述

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

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.

软件
前端设计
程序设计
Java相关