作者:汽车时尚宠 | 来源:互联网 | 2023-02-09 08:10
当我有这样的课程
public class MyClass {
private ClassA classA;
private ClassB classB;
}
我的equals和hascode函数经常会像这样混乱
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((classB == null) ? 0 : classB.hashCode());
result = prime * result + ((classA == null) ? 0 : classA.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyClass other = (MyClass) obj;
if (classB == null) {
if (other.classB != null)
return false;
} else if (!classB.equals(other.classB))
return false;
if (classA == null) {
if (other.classA != null)
return false;
} else if (!classA.equals(other.classA))
return false;
return true;
}
所以我开始忽略有人会将苹果与香蕉进行比较.我的应用程序中的HashSets或HashMaps总是包含相同的对象类型...我从未创建过List并开始将Integer与String混合.
@Override
public int hashCode() {
return classB.hashCode();
}
@Override
public boolean equals(Object obj) {
MyClass other = (MyClass) obj;
return other.classB.equals(this.classB) && other.classA.equals(this.classA);
}
忽视不常见的情况并抛出异常是不好或好的做法?我认为当比较完整的不同类时,这通常是一个错误.
1> Sean Patrick..:
允许equals()
或hashCode()
抛出异常是非常糟糕的做法(我建议您阅读Effective Java的详细信息).
此外,您的方法不必要地复杂.从Java 7开始,这几乎就是编写这些方法的规范方法:
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}else if (o instanceof MyClass) {
// some will argue that the line above should have a
// .getClass() check instead of an instanceof check.
// those people also need to read Effective Java :-)
MyClass that = (MyClass) o;
return Objects.equals(this.classA, that.classA)
&& Objects.equals(this.classB, that.classB)
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(classA, classB);
}