views:

68

answers:

3

I'm storing a (possibly large) number of objects in memory that I want to refer to by long identifiers. Currently, I'm using a standard HashMap<Long, MyClass>. I was wondering if there might be a better way to do it, since intuitively, I'd think that wrapping long in a Long doesn't really make sense.

Note that, as of now, this question is still somewhat academic, so far, I haven't any performance problems with the current solution. It may well be that it never even becomes one. Soon, however, I expect substantial growth in the data I need to process, and I'm starting to compile a list of ideas at what I might want to take a look if things get slow.

A: 

You could write your own HashMap implementation using a primitive long for the key instead of a Long wrapper. Its not hard to cut and paste the JDK HashMap to do this.

You can leave this until you need it as the refactor should be simple. Java's autoboxing will make it possible to just drop in your new class. Call to java.util.HashMap with a primitive long will now work without being boxed. You will need to change code that expects an null for the missing key case to check for a zero instead.

David Tinker
I was expecting that someone already did that, and as extraneon has noted, this seems to be true.
Hanno Fietz
A: 

I'd be very surprised if the Maps provided by Java would not be sufficient for your needs. If your data set grows so large that memory would be a problem it would make a lot more sense to look into using a database.

willcodejavaforfood
The objects are coming from a database, so the set may grow large. As I noted, so far, I'm not experiencing problems. I'm currently just looking through the codebase and trying to get a feel of what might be worth looking at further down the road.
Hanno Fietz
@Hanno Fietz - Fair enough :)
willcodejavaforfood
+3  A: 

First of all, I really doubt this should be necessary. But if it does, take a look at TLongObjectHashMap in trove4j. That does exactly that :)

For the record, it does not wrap a hashmap but uses arrays to store state.

There's also some benchmarks on the trove site, that may help.

extraneon
Thanks, I'll add that to my research list and pull it out if there's ever an issue with the Map I'm using now.
Hanno Fietz