The analyzer detected that the overridden equals method lacks a null check for the argument, violating the standard contract.
Look at the example:
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (getClass() != object.getClass()) {
return false;
}
Foo another = (Foo) object;
return type.equals(another.type) &&
name.equals(another.name);
}
The equals method implements a class match check and field comparison. However, the developer did not take into account that the argument could be a null reference. This may result in a NullPointerException thrown when getClass is called.
According to the documentation, overriding the Object.equals method should return false when a null reference is passed, rather than throw an exception. This is especially important if the class is used in collections.
The fixed example:
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
Foo another = (Foo) object;
return type.equals(another.type) &&
name.equals(another.name);
}
This diagnostic rule is classified as:
Was this page helpful?
Your message has been sent. We will email you at
If you do not see the email in your inbox, please check if it is filtered to one of the following folders: