For Programmers: Free Programming Magazines  


Home > Archive > Java Help > November 2005 > HashMap with primitive int key









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author HashMap with primitive int key
Andrew E

2005-11-28, 9:58 pm

Dear All,

I have a class like this:

class CustomerOrder {
int globalID;
...
}

I have an array of these.
I'd like to store an index of globalIDs, so I can do:

CustomerOrder o = index.get(123)

I could modify my class to be:

class CustomerOrder {
Integer globalID;
...
}

Perhaps it is my C++ background, but the idea of allocating an object for every
ID when I can just use an int bothers me.

I figure a HashMap is the right tool of choice, e.g.:

HashMap<Integer, CustomerOrder> index = new ...


Has anyone out there already written a modified hashmap class that uses int as
the key?

Thanks for any tips :)

Andrew
Thomas Hawtin

2005-11-28, 9:58 pm

Andrew E wrote:
>
> CustomerOrder o = index.get(123)


> Perhaps it is my C++ background, but the idea of allocating an object for every
> ID when I can just use an int bothers me.


The overhead for allocating a small object is actually very small. It
shouldn't come as a surprise that Java runtimes are heavily optimised
for allocating small, short-lived objects. I get around 30-40 cycles on
my PII. Can be as low as 10 instructions on some architectures.

You've actually picked a number in an interesting range. Integer.valueOf
(which autoboxing uses) always returns the same value for at least those
integers in [-128, 127]. Years ago when I was dealing with an applet
which generated lots of small Integers, I used an array of the first 256
to deal with the almost always small IDs. If nothing else it cleared
some mess off the profiler.

If you are dealing with large numbers but often repeating the same
values there is a cunning thread-safe trick that works from 1.5:

http://jroller.com/page/tackline?entry=fast_immutables

(Note comments.)

> Has anyone out there already written a modified hashmap class that uses int as
> the key?


IIRC there is a apache Jakarta Commons Primitives subsubsubproject for
primitive collections. But I suggest that you first visit Mr OptimizeIT,
Mr JProbe or one of their friends before adding dependencies and
obscurities. ;)

Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com