Double in HashMap

Short answer: Don’t do it

Long answer: Here is how the key is going to be computed:

The actual key will be a java.lang.Double object, since keys must be objects. Here is its hashCode() method:

public int hashCode() {
  long bits = doubleToLongBits(value);
  return (int)(bits ^ (bits >>> 32));
}

The doubleToLongBits() method basically takes the 8 bytes and represent them as long. So it means that small changes in the computation of double can mean a great deal and you will have key misses.

If you can settle for a given number of points after the dot – multiply by 10^(number of digits after the dot) and convert to int (for example – for 2 digits multiply by 100).

It will be much safer.

Leave a Comment