The equals()
method is called on an object that does not implement equals()
.
When comparing objects, developers developers usually want to compare properties of objects. However, calling equals()
on a class (or any super class/interface) that does not explicitly implement equals()
results in a call to the equals()
method inherited from java.lang.Object
. Instead of comparing object member fields or other properties, Object.equals()
compares two object instances to see if they are the same. Although there are legitimate uses of Object.equals()
, it is often an indication of buggy code.
Example 1:
public class AccountGroup
{
private int gid;
public int getGid()
{
return gid;
}
public void setGid(int newGid)
{
gid = newGid;
}
}
...
public class CompareGroup
{
public boolean compareGroups(AccountGroup group1, AccountGroup group2)
{
return group1.equals(group2); //equals() is not implemented in AccountGroup
}
}
[1] Standards Mapping - Common Weakness Enumeration - (CWE) CWE ID 398