我有一个关于汽车登记的项目。我有一个名为RegNo的类,它实现了可比较接口。它应该包含被覆盖的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;
}
}发布于 2021-04-16 11:01:16
尝试委托字符串的方法
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();
}
}https://stackoverflow.com/questions/67118134
复制相似问题