Skip to content

False negative on EQ_ALWAYS_TRUE and EQ_ALWAYS_FALSE #3528

@csrma

Description

@csrma

Spotbugs detects the EQ_ALWAYS_TRUE issue in the following code.

class AlwaysTrueEquals {

    @Override
    public boolean equals(Object obj) {
        return true;
    }

    @Override
    public int hashCode() {
        return 42;
    }

    public static void main(String[] args) {
        AlwaysTrueEquals obj1 = new AlwaysTrueEquals();
        AlwaysTrueEquals obj2 = new AlwaysTrueEquals();

        System.out.println("obj1.equals(obj2): " + obj1.equals(obj2));
        System.out.println("obj2.equals(obj1): " + obj2.equals(obj1));
    }
}

However, if the equals method is re-written as the following, the error is no longer raised. The updates do not seem to have changed the return value in anyway, it's still a hard-coded true returned. I am not sure if this is a bug or if I'm doing anything silly, because the code seems very simple.

@Override
public boolean equals(Object obj) {
    boolean checkEqual = (obj instanceof AlwaysTrueEquals);
    System.out.println(checkEqual);
    return true;
}

Exactly similar issue is also observable with EQ_ALWAYS_FALSE as well.
Note: The (obj instanceof AlwaysTrueEquals) is completely optional and the issue is reproducible without this. It is only added to suppress the EQ_UNUSUAL error.

Spotbugs: 4.9.3
Java: Jdk 17 and Jdk 21
Run Method: CLI as:

javac AlwaysTrueEquals.java && \
    java -jar $SPOTBUGS_JAR -textui -effort:max *.class

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions