以下示例代码之一是java equals方法的错误实现。它违反了一致性规则。哪一个违反了规则,请指出方法在何处以及如何违反一致性规则?
示例1
public class WrongEquals {
private final AtomicInteger counter;
public WrongEquals(int start) {
this.counter = new AtomicInteger(start);
}
public int getCount() {
return counter.getAndDecrement();
}
@override public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WrongEquals that = (WrongEquals) o;
return counter.get() == that.getCount();
}
@override public int hashCode() {
return counter.hashCode();
}
}
exmaple 2
public class WrongEquals {
private final AtomicInteger counter;
public WrongEquals(int start) {
this.counter = new AtomicInteger(start);
}
public int getCount() {
return counter.getAndDecrement();
}
@override public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WrongEquals that = (WrongEquals) o;
return getCount() == that.getCount(); //changed here
}
@override public int hashCode() {
return counter.hashCode();
}
}
答案 0 :(得分:2)
您应该了解创建equals方法时应该满足的许多属性。它们具有反身性,对称性,传递性和一致性。如果您需要,Google会提供更多详细信息。
考虑到这些属性,尝试编写一些代码,在每个类上测试它们并查看哪些代码失败。这应该相当容易,因为你已经有了类的代码。