Double in HashMap

后端 未结 8 1217
借酒劲吻你
借酒劲吻你 2020-11-28 11:17

I was thinking of using a Double as the key to a HashMap but I know floating point comparisons are unsafe, that got me thinking. Is the equals method on the Double class als

8条回答
  •  情书的邮戳
    2020-11-28 11:39

    I think you are right. Although the hash of the doubles are ints, the double could mess up the hash. That is why, as Josh Bloch mentions in Effective Java, when you use a double as an input to a hash function, you should use doubleToLongBits(). Similarly, use floatToIntBits for floats.

    In particular, to use a double as your hash, following Josh Bloch's recipe, you would do:

    public int hashCode() {
      int result = 17;
      long temp = Double.doubleToLongBits(the_double_field);
      result = 37 * result + ((int) (temp ^ (temp >>> 32)));
      return result;
    }
    

    This is from Item 8 of Effective Java, "Always override hashCode when you override equals". It can be found in this pdf of the chapter from the book.

    Hope this helps.

提交回复
热议问题