When browsing the source code of Guava, I came across the following piece of code (part of the implementation of hashCode
for the inner class CartesianSet
):
int adjust = size() - 1;
for (int i = 0; i < axes.size(); i++) {
adjust *= 31;
adjust = ~~adjust;
// in GWT, we have to deal with integer overflow carefully
}
int hash = 1;
for (Set<E> axis : axes) {
hash = 31 * hash + (size() / axis.size() * axis.hashCode());
hash = ~~hash;
}
hash += adjust;
return ~~hash;
Both of adjust
and hash
are int
s. From what I know about Java, ~
means bitwise negation, so adjust = ~~adjust
and hash = ~~hash
should leave the variables unchanged. Running the small test (with assertions enabled, of course),
for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) {
assert i == ~~i;
}
confirms this. Assuming that the Guava guys know what they are doing, there must be a reason for them to do this. The question is what?
EDIT As pointed out in the comments, the test above doesn't include the case where i
equals Integer.MAX_VALUE
. Since i <= Integer.MAX_VALUE
is always true, we will need to check that case outside the loop to prevent it from looping forever. However, the line
assert Integer.MAX_VALUE == ~~Integer.MAX_VALUE;
yields the compiler warning "Comparing identical expressions", which pretty much nails it.