我应该在TreeMap中使用Double作为键吗? [英] Should I use Double as keys in a TreeMap?

查看:678
本文介绍了我应该在TreeMap中使用Double作为键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Double in HashMap 的答案所述,双面不应在HashMaps中使用,因为他们很难比较平等。我相信我的情况不同,但我想我会要求确保,因为我没有看到任何关于这个。



我要有一个系列与对象相关联的双精度值,我希望它们按照双精度值排序。是TreeMap合适的解决方案吗?会有更好的一个吗? double值是由一系列数学生成的,所以重复值的可能性非常低。



编辑:我应该澄清:我需要的是有这个列表的对象按照它们关联的双精度排序。双精度值将被舍弃,我永远不会调用 map.get(key)

方案


双击不应在HashMaps中使用,因为它们难以比较是否相等。




  • 你会尝试 get

    如果,那么关于难以比较的推理适用于基于某些键的原因?




    • 你应该避免这样的数据结构(或者总是依赖 tailMap / headMap /


    • 如果没有 for(Double key:map.keySet())... 或迭代 entrySet



您可以使用 Double


double值是由一系列数学生成的,因此重复值的可能性极低。 / strong>





  • 这是一个错误

    如果,则不是 正确的数据结构使用。例如,您可以使用


  • 如果没有


$ b $

b

As described in the answer to Double in HashMap, Doubles shouldn't be used in HashMaps because they are difficult to compare for equality. I believe my case is different, but I thought I'd ask to make sure since I didn't see anything about this.

I'm going to have a series of double values associated with objects, and I want them to be sorted by the double values. Is TreeMap an appropriate solution? Would there be a better one? The double values are generated a bunch of math, so the likelihood of a duplicate value is extremely low.

EDIT: I should clarify: all I need is to have this list of objects sorted by the doubles they're associated with. The values of the doubles will be discarded and I'll never call map.get(key)

解决方案

Doubles shouldn't be used in HashMaps because they are difficult to compare for equality.

  • Will you ever try to get the values based on certain keys?

    • If yes, then the reasoning about "difficult to compare" applies and you should probably avoid such data structure (or always rely on tailMap / headMap / submap and fetch ranges of the map).

    • If no (i.e. you'll typically just do for (Double key : map.keySet()) ... or iterate over the entrySet) then I would say you're fine using Double as keys.

The double values are generated a bunch of math, so the likelihood of a duplicate value is extremely low.

  • Is it a bug if you actually do get a duplicate?

    • If yes then it's not the right data structure to use. You could for instance use a Multimap from Guava instead.

    • If no, (i.e. it doesn't matter which of the two values it maps to, because they can only differ by a small epsilon anyway) then you should be fine.

这篇关于我应该在TreeMap中使用Double作为键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆