java - 对于我编写的以下代码,我应该如何覆盖 java 中的 hashCode 和 equals 方法
问题描述
我有一个关于汽车登记的项目。我有一个名为 RegNo 的类,它实现了类似的接口。当我在 hashmap 中使用它时,它应该包含被覆盖的 equals 和 hashCode 函数。请帮助我解决这个问题。类代码如下:
package main;
public class RegNo implements Comparable<RegNo> {
private final String regNo;
public RegNo(String regNo)
{
this.regNo = regNo;
}
/*
* implementing the compareTO method which is defined
* in Comparable class as an abstract method
* the method returns 0 if both the registration numbers being compared are equal
* it returns 1 if the regNo of the object calling this method is lexicographically greater than the parameter
* and the method returns a -1, if the regNo of the parameter is greater than the object calling the method
* */
@Override
public int compareTo(RegNo reg) {
// TODO Auto-generated method stub
if(this.regNo == reg.regNo) //both the registration numbers are equal
return 0;
else if(this.regNo.compareTo(reg.regNo) > 0)
return 1;
else
return -1;
}
}
解决方案
尝试委托字符串的方法
public static class RegNo implements Comparable<RegNo> {
private final String regNo;
public RegNo(String regNo)
{
this.regNo = regNo;
}
@Override
public int compareTo(RegNo reg) {
return regNo.compareTo(reg.regNo);
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
if (this == o) return true;
RegNo regNo1 = (RegNo) o;
return regNo.equals(regNo1.regNo);
}
@Override
public int hashCode() {
return regNo.hashCode();
}
}
推荐阅读
- angular - Angular:保留可观察对象的先前值
- python - 如何最小化单个 .jpg 文件下载的下载时间?
- sql - 使用 trunc(date) 的原因是什么
- sql - 基于日期的 Postgresql 条件连接
- javascript - 是的,带有 vee-validate 和 typescript 的模式
- java - 带有 \\\\ 正则表达式的 Java 验证注释 @Pattern 无法正常工作
- c# - 如何更改 WSDL 标记属性值
- java - RabbitMQ 传递确认超时
- java - 带有 JSON 的 Java HTTP POST 请求
- apache-kafka - GKE 中的 Strimzi kafka 设置