V6134. It is not recommended to throw exceptions from the 'equals' method.
The analyzer has detected that an exception is explicitly thrown in the equals method. This behavior is not recommended as this method may be used in contexts where throwing an exception is not expected. This can occur both in the user's code and when interacting with the standard library.
The example:
class User {
....
@Override
public boolean equals(Object o) {
if (o == null) {
throw new IllegalArgumentException("....");
}
....
}
}
According to its contract, the Object.equals method returns false if null is passed as an argument. However, in this overridden method, an IllegalArgumentException is thrown instead. This can lead to issues when the object is used in a collection.
The example:
List<User> users = new ArrayList<>();
users.add(null);
users.add(new User("a@example.com"));
//....
users.contains(new User("b@example.com")); // IllegalArgumentException
The ArrayList.contains method uses equals to compare the passed argument with the elements of the collection. Since the collection contains an object that references null, passing this object to the equals method results in the IllegalArgumentException.
To avoid such issues, return the appropriate boolean value instead of throwing an exception.
The fixed example:
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
....
}