[ACCEPTED]-equals method overrides equals in superclass and may not be symmetric-java
Accepted answer
It says that the contract of equals()
implies that, a.equals(b)
is 6 true if and only if b.equals(a)
is true.
If B extends 5 A, in A.equals(Object obj)
you probably will have
if !(obj instanceof A) return false;
and in B.equals(Object obj)
you 4 will have
if !(obj instanceof B) return false;
Here is the asymmetry: an instance 3 of B makes (b instanceof A
) true, while an instance of 2 A makes (a instanceof B
) false. So it means a risk than 1 a.equals(b)
is true and b.equals(a)
is false.
You can use the similar construction to 1 prevent this error:
public boolean equals(final Object obj)
{
if (obj == null || getClass() != obj.getClass())
{
return false;
}
// ...
instead of
public boolean equals(final Object obj)
{
if (!(o instanceof UniversalIDDefinition))
{
return false;
}
// ...
You can use this too :
if (obj == null || !MyClass.class.isAssignableFrom(obj.getClass())) {
return false;
}
0
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.