Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java FindBugs: Suspicious comparison of Long references

Tags:

java

findbugs

FindBugs recognizes the following bug in my code:

Suspicious comparison of Long references

I have tried Googling this particular error but with no luck. As far as I know comparing fields of data type Long should be done with == operator.

if (materialDefinition.getId() == definitionToRemoveFromClass.getId()) {
    //...
}

I am certain both methods .getId() return a Long.

Is this really an issue and if so, how do I fix it?

like image 718
Anonymoose Avatar asked Dec 07 '22 01:12

Anonymoose


1 Answers

Is this really an issue and if so, how do I fix it?

Yes, you're comparing references not values, so two different Long instances with identical values will result in that comparison being false. You should use Long#equals() instead:

final Long id1 = materialDefinition.getId();
final Long id2 = definitionToRemoveFromClass.getId();

if (id1.equals(id2)) {
    //...
}

If getId() can return null, then also be sure to include the appropriate null check (although getId() doesn't sound like a method that should be returning null).

like image 52
arshajii Avatar answered Dec 26 '22 00:12

arshajii