Double in HashMap

后端 未结 8 1156
借酒劲吻你
借酒劲吻你 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 12:01

    It depends on how you store and access you map, yes similar values could end up being slightly different and therefore not hash to the same value.

    private static final double key1 = 1.1+1.3-1.6;
    private static final double key2 = 123321;
    ...
    map.get(key1);
    

    would be all good, however

    map.put(1.1+2.3, value);
    ...
    map.get(5.0 - 1.6);
    

    would be dangerous

    0 讨论(0)
  • 2020-11-28 12:06

    Maybe BigDecimal get you where you want to go?

    0 讨论(0)
提交回复
热议问题