Can I generate warnings when we try to compare Java boxed primitives with "==" instead of ".equals"?

159 views Asked by At

NPEs are described as a "billion dollar mistake". I have to believe a close second may be comparing boxed primitives with "==" instead of .equals(...).

When we have a part of our codebase that returns a Long instead of a long, for example:

class Car {
  Long speed;
}

and

Car carA, carB;
boolean res1 = carA.getSpeed() == carB.getSpeed(); // could fail if the speeds are equal because the wrappers are distinct.

boolean res2 = Objects.equals(carA.getSpeed(), carB.getSpeed()); // compares by value and works

this kind of thing is easy to miss in a PR. Is there a way to generate a warning to catch this situation? We use sonar, FWIW.

3

There are 3 answers

1
cakedmypants On BEST ANSWER

You could also use the spotbugs-maven-plugin which would make the build fail with RC: Suspicious reference comparison (RC_REF_COMPARISON) if it encounters code like this.

1
Brandon Ruiz Acosta On

If you use IntelliJ this will be warned by default

See https://www.jetbrains.com/help/idea/list-of-java-inspections.html#code-maturity for mor details

1
Lonzak On

I would advice you to use the sonar server (community edition). There specific are rules for equals. There are plugins (SonarLint) to connect your favourite IDEs and also Plugins for the server itself to add other features (like spotbugs etc).

(I am not affiliated with sonarqube but a user of the free sonar server)