Discussion:
HashMap Keys?
(too old to reply)
Ken
2004-07-02 02:51:35 UTC
Permalink
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
2004-07-14 07:00:33 UTC
Permalink
Post by Ken
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
2004-07-16 09:57:52 UTC
Permalink
Post by Ken
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
2005-07-20 04:39:30 UTC
Permalink
Post by Jonni Gani
Post by Ken
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.
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
2004-07-22 15:36:49 UTC
Permalink
Post by Ken
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
Hi Ken

I always use Strings as keys in a hash map and I have never
encountered problems in either effiency or effectiveness

Steve
Loading...