Java Gotchas
Java Gotchas
While programming in Java, I’ve run across a few gotchas with libraries that are worth pointing out.
BigDecimal
hashCode
andequals
are not defined on the conceptual value of the number. For example,new BigDecimal("1.1").equals(new BigDecimal("1.10")) == false
, because of internal differences with how they store the number. If you need to compute a hash code for them, usehash(b.doubleValue())
. If you need to compare for equality, useb1.compareTo(b2) == 0
.
BigInteger
- For negative numbers,
bitLength
can be different than what you expect. For example,new BigInteger("-128").bitLength() == 7
, because the sign bit is not counted as part of the bit length, and it can be stored in 8 bits using twos-complement. What you most likely want isb.abs().bitLength()
, or if that is expensive and over-estimation is not an issue, you can add one to the length.
JUnit
- JUnit and older JVMs do not guarantee the order that unit tests will be run in. While JUnit poo-poo’s test order as a sign of bad coding, it does serve one very important purpose: re-produciblity of fuzz tests. The workaround: generate a random seed, log it, then reset the random generator back to the same seed at the start of each test case.