[ACCEPTED]-Java FindBugs: Suspicious comparison of Long references-findbugs
Is this really an issue and if so, how do 7 I fix it?
Yes, you're comparing references not values, so 6 two different Long
instances with identical 5 values will result in that comparison being 4 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 3 null
, then also be sure to include the appropriate 2 null
check (although getId()
doesn't sound like a method 1 that should be returning null
).
You may want to do something like this.
public static boolean equals(Long a, Long b){
if (a==null && b==null) return true;
else if ((a==null) != (b==null)) return false;
else return a.equals(b);
}
0
You'd better use if (materialDefinition.getId().equals(definitionToRemoveFromClass.getId()))
Be sure that materialDefinition.getId()
is not null.
To 2 compare these values (< >) you can use 1 .compareTo()
method :
A == B: A.compareTo(B) == 0
A < B: A.compareTo(B) < 0
A > B: A.compareTo(B) > 0
Yes it's a bad smell, and you should use 11 the equals()
method instead, as explained @arshajii 10 above.
What I've found most intriguing is 9 the fact that such comparison might even 8 work sometimes, like starting with small 7 values (-128 to 127), and will break for 6 larger numbers. For example:
@Test
public void compareSmallIds() {
Long id1 = 127L;
Long id2 = 127L;
Assert.assertTrue(id1 == id2);
Assert.assertTrue(id1.equals(id2));
Assert.assertTrue((long) id1 == (long) id2);
Assert.assertTrue(id1.longValue() == id2.longValue());
}
@Test
public void compareIds() {
Long id1 = 500L;
Long id2 = 500L;
Assert.assertFalse(id1 == id2);
Assert.assertTrue(id1.equals(id2));
Assert.assertTrue((long) id1 == (long) id2);
Assert.assertTrue(id1.longValue() == id2.longValue());
}
It seems this 5 behavior is based on number cache policy 4 definition, with byte values range as default. But 3 definitely, code with non-primitive values 2 should not rely on the ==
operator for value 1 comparison!
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.