Hi. I'm looking for advice on using keys for a HashMap.
Is it typical to just use a string as a key, e.g., "Item A", "Item B",
etc.? Or are other approaches better? Since the key is just an
Object, I thought there might be some other approach commonly used
that is more efficient/effective.
Thanks for any advice!
Ken
GG - 14 Jul 2004 08:00 GMT
> Hi. I'm looking for advice on using keys for a HashMap.
It all depends on what you're trying to do, duh :). First of all, check out
how the HashMap works at all, the source is available. See if you understand
the requirements for equals() / hashCode(). See if you can follow why
Strings are common choice (well, also because it's just easy :). But maybe
that's not what you want. What problem are you trying to solve?
Jonni Gani - 16 Jul 2004 10:57 GMT
> Is it typical to just use a string as a key, e.g., "Item A", "Item B",
> etc.? Or are other approaches better? Since the key is just an
> Object, I thought there might be some other approach commonly used
> that is more efficient/effective.
Don't worry too much whether using String is more efficient (generally
it's bad to worry about optimization during implementation). You
should use whatever object which makes the best sense in your
situation. Note that Map keys must be *immutable*, otherwise the Map
may not work properly. Strings are immutable.
Adam Maass - 20 Jul 2005 05:39 GMT
>> Is it typical to just use a string as a key, e.g., "Item A", "Item B",
>> etc.? Or are other approaches better? Since the key is just an
[quoted text clipped - 6 lines]
> situation. Note that Map keys must be *immutable*, otherwise the Map
> may not work properly. Strings are immutable.
Not quite. Objects used as keys in a Map must not change while they are in
use as keys in a Map. Immutable objects never change once constructed, so
they meet this requirement.
-- Adam
Stephen Curtin - 22 Jul 2004 16:36 GMT
> Hi. I'm looking for advice on using keys for a HashMap.
>
[quoted text clipped - 6 lines]
>
> Ken
Hi Ken
I always use Strings as keys in a hash map and I have never
encountered problems in either effiency or effectiveness
Steve