Should I use Double as keys in a TreeMap?

collections, java, sorting, treemap

Solution

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.

Problem

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)`

Original source

Related problems