Menu

#2 incorrect implementation of IdentityComparator

open
nobody
None
5
2010-10-09
2010-10-09
Ximin Luo
No

IdentityComparator is implemented incorrectly.

return n1 - n2;

will cause approximately 75% of comparisons to return -1, due to integer overflow. example:

$ bsh
BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh % int a = 0x7fffffff, b = -1;
bsh % System.out.println(Integer.toHexString(a));
7fffffff
bsh % System.out.println(Integer.toHexString(b));
ffffffff
bsh % System.out.println(b-a);
-2147483648
bsh % System.out.println(a-b);
-2147483648

As you can see both compare(a,b) and compare(b,a) return -1, breaking the contract of compare().

The correct implementation is, ironically, the longer, commented-out version of the code. Just uncomment it to fix the bug.

Discussion


Log in to post a comment.

MongoDB Logo MongoDB