What to use as HashMap Key?

Discussion in 'Java' started by Ken, Jul 2, 2004.

  1. Ken

    Ken Guest

    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
     
    Ken, Jul 2, 2004
    #1
    1. Advertising

  2. Ken

    Chris Smith Guest

    Ken wrote:
    > 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.


    There's no answer to the question you asked. HashMaps are used all the
    time, and sometimes it's best to use a String as a key and sometimes
    it's best to use something different. If I had to guess, I'd say that
    String is used more often than any other class, but that still doesn't
    make it okay to use String when it's the wrong choice. I certainly
    wouldn't go out of my way to use a String when something else is more
    appropriate to a specific application.

    So, if you want advice, then you'll need to give a specific scenario.

    --
    www.designacourse.com
    The Easiest Way to Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Jul 2, 2004
    #2
    1. Advertising

  3. Ken

    Roedy Green Guest

    On 1 Jul 2004 19:48:05 -0700, (Ken) wrote or quoted :

    >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.


    If you can get away with something more compact or that you can
    compare faster, so much the better. If you could scrunch it down to
    an dense int, then you would not need a HashMap. You could use an
    array.

    The most likely common alternative is a Long.

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jul 2, 2004
    #3
  4. On Thu, 01 Jul 2004 19:48:05 -0700, Ken wrote:

    > 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


    Remember, any Object used as a key should have a fixed hash code and it's
    definition of "equals" should not change throughout its life cycle. This
    is most easily accomplished by using an immutable Object (such as String
    or Integer).

    HTH,
    La'ie Techie
     
    =?UTF-8?b?TMSByrtpZSBUZWNoaWU=?=, Jul 2, 2004
    #4
  5. (Ken) wrote in message news:<>...
    > 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.


    Talking about performance, two things enter the equation: how the
    hash code of your keys is computed and how fast their
    ..equals() method is.

    Strings:
    the hash code is computed by somehow mangling all characters,
    .equals() has to compare the two strings character by character.

    Integer:
    the hash code is the value itself,
    .equals() compares the two values with '=='.

    Guess yourself which one is faster on the average and then
    dismiss performance considerations and first go
    for a clean, easy to maintain design when choosing the key
    type.

    Harald Kirsch
     
    Harald Kirsch, Jul 2, 2004
    #5
  6. Ken

    Guest

    (Ken) wrote in message news:<>...
    > 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


    I always find it useful to name maps xToY, e.g.,

    Map nameToAddress = new HashMap();
    Map titleToBook= new HashMap();
    Map actionToConsequence = new HashMap();

    Although this doesn't help you in your quest of a type of class to use
    a key, it helps to show you precisely what your Map is mapping.

    Just a thought ...

    ..ed

    www.EdmundKirwan.com - Home of The Fractal Class Composition
     
    , Jul 2, 2004
    #6
  7. Ken

    kk_oop Guest

    Harald Kirsch wrote:

    >
    >Guess yourself which one is faster on the average and then
    >dismiss performance considerations and first go
    >for a clean, easy to maintain design when choosing the key
    >type.
    >
    > Harald Kirsch
    >


    This was my sense. After I poplulate the HashMap in one class, other
    classes will need to access its elements. I figure a String will
    provide a good, easy to understand abstraction for each element. In my
    case I have a set of rules. So I'd make my key something like "X Factor
    Rule" or "Y Factor Rule", where "X Factor" and "Y Factor" are
    recognizable names from our domain.

    How about combining performance and readability by making a "Key" class
    that contains static final int fields. Something like this:

    class HashKeys
    {
    HashKeys ( ) { }

    protected static final int X_FACTOR_RULE = 1;
    protected static final int Y_FACTOR_RULE = 2;
    }

    Then, for example, I can just use HashKeys.X_FACTOR_RULE as a key value.

    Alternatively, I can take the Interger approach.

    class HashKeys
    {
    HashKeys( )
    {
    this.X_FACTOR_RULE = new Integer(1);
    this.Y_FACTOR_RULE = new Integer(2);
    }
    protected Integer X_FACTOR_RULE;
    protected Integer Y_FACTOR_RULE;
    }

    In that case, I'd make HashKeys a Singleton.

    Note that I use protected since the Hash Table will be used only by
    classes in the same package as itself. Do either of these approaches
    seem reasonable? One better than the other? Other suggestions? I'm
    inclined to go with the first approach because it seems less complex,
    but I don't know if there's any catch I'm missing.

    Thanks again for any recommendations!

    Ken
     
    kk_oop, Jul 2, 2004
    #7
  8. Ken

    Praveen Guest

    What is a immutable object.?

    LÄÊ»ie Techie wrote:
    > On Thu, 01 Jul 2004 19:48:05 -0700, Ken wrote:
    >
    >
    >>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

    >
    >
    > Remember, any Object used as a key should have a fixed hash code and it's
    > definition of "equals" should not change throughout its life cycle. This
    > is most easily accomplished by using an immutable Object (such as String
    > or Integer).
    >
    > HTH,
    > La'ie Techie
    >
     
    Praveen, Jul 2, 2004
    #8
  9. Ken

    Roedy Green Guest

    Roedy Green, Jul 2, 2004
    #9
  10. Ken

    Roedy Green Guest

    On Fri, 02 Jul 2004 07:44:46 -0400, "kk_oop<no spam>" <"kk_oop<no
    spam>"@yahoo.com> wrote or quoted :

    >Then, for example, I can just use HashKeys.X_FACTOR_RULE as a key value.


    Hashtables are for lookup by unique identifier. They are not a way of
    classifying, dividing a set into subsets. So to me, your code makes
    no sense.

    See http://mindprod.com/jgloss/hashcode.html for tips on computing
    them.

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jul 2, 2004
    #10
  11. Ken

    Chris Smith Guest

    La'ie Techie wrote:
    > Remember, any Object used as a key should have a fixed hash code and it's
    > definition of "equals" should not change throughout its life cycle. This
    > is most easily accomplished by using an immutable Object (such as String
    > or Integer).


    This is, indeed, a problem for some poorly conceived objects (including
    all instances of mutable classes from the Collections API, for example).
    Most mutable classes, though, correctly inherit the default
    implementations of hashCode and equals from Object, and those
    implementations are quite suitable for use as keys in a HashMap.

    The problem is that various people have decided on their own meaning for
    when one object "equals" another, and those meanings are mutually
    incompatible. Ironically, the meaning defined for the objects *in* a
    HashMap is different from (and incompatible with) the meaning defined
    for HashMap itself!

    It would be far better if objects that wanted to establish some concept
    of temporary similarity or equivalence of contents would define their
    own methods for doing so, instead of abusing equals for that purpose;
    but we've now reached the point of having misuse of equals codified in
    the API specification. It can no longer be undone.

    --
    www.designacourse.com
    The Easiest Way to Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Jul 2, 2004
    #11
  12. Ken

    Chris Smith Guest

    "kk_oop<no spam>" <"kk_oop<no spam>"@yahoo.com> wrote:
    > How about combining performance and readability by making a "Key" class
    > that contains static final int fields. Something like this:
    >
    > class HashKeys
    > {
    > HashKeys ( ) { }
    >
    > protected static final int X_FACTOR_RULE = 1;
    > protected static final int Y_FACTOR_RULE = 2;
    > }


    If you know all of the possible key values at compile time, then don't
    use a HashMap at all! Define a class to hold the set of values.

    --
    www.designacourse.com
    The Easiest Way to Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Jul 2, 2004
    #12
  13. Ken

    Chris Smith Guest

    "kk_oop<no spam>" <"kk_oop<no spam>"@yahoo.com> wrote:
    > Well, I know the key values at compile time, but I don't know the values
    > that will be stored with the keys. So in my example, when I called put(
    > ), it would be given HashKeys.X_FACTOR_RULE as the key and some other
    > object as the rule item to store. That item will not be known at
    > compile time. However, it will need to be stored and accessed by a
    > unique identifier (which would be the value of X_FACTOR_RULE).
    >
    > Does that make sense?


    I'd still say no. What about:

    public class MyValues
    {
    private Object xFactorRule = null;
    private Object yFactorRule = null;
    private Object zFactorRule = null;

    // getter and setter methods
    }

    --
    www.designacourse.com
    The Easiest Way to Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Jul 3, 2004
    #13
  14. Ken

    kk_oop Guest

    Chris Smith wrote:

    >"kk_oop<no spam>" <"kk_oop<no spam>"@yahoo.com> wrote:
    >
    >
    >>How about combining performance and readability by making a "Key" class
    >>that contains static final int fields. Something like this:
    >>
    >>class HashKeys
    >>{
    >> HashKeys ( ) { }
    >>
    >> protected static final int X_FACTOR_RULE = 1;
    >> protected static final int Y_FACTOR_RULE = 2;
    >>}
    >>
    >>

    >
    >If you know all of the possible key values at compile time, then don't
    >use a HashMap at all! Define a class to hold the set of values.
    >


    Well, I know the key values at compile time, but I don't know the values
    that will be stored with the keys. So in my example, when I called put(
    ), it would be given HashKeys.X_FACTOR_RULE as the key and some other
    object as the rule item to store. That item will not be known at
    compile time. However, it will need to be stored and accessed by a
    unique identifier (which would be the value of X_FACTOR_RULE).

    Does that make sense?

    I suppose an alternative would be to use these key values as indexes
    into an ArrayList. Would that be a better approach?

    Thanks again,

    Ken



    >
    >
    >
     
    kk_oop, Jul 3, 2004
    #14
  15. Ken

    Hemal Pandya Guest

    =?UTF-8?b?TMSByrtpZSBUZWNoaWU=?= <laie@win_remove_get_nospam_solutions.com> writes:

    > On Thu, 01 Jul 2004 19:48:05 -0700, Ken wrote:
    >
    >> 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

    >
    > Remember, any Object used as a key should have a fixed hash code and it's
    > definition of "equals" should not change throughout its life cycle. This
    > is most easily accomplished by using an immutable Object (such as String
    > or Integer).
    >


    I assume the Object here is instance member. Maybe I am wrong, but how
    will this help if that member is itself not final?

    When using non-primitive type members, I like to compute the hash
    code from hashCode method of final members.

    BTW, I believe this is a Big Gotcha. I am surprised that
    http://mindprod.com/jgloss/hashcode.html does not address this.

    > HTH,
    > La'ie Techie
     
    Hemal Pandya, Jul 6, 2004
    #15
  16. Ken

    princebadshah

    Joined:
    Dec 5, 2008
    Messages:
    2
    So If I want to make string as Key to make search efficient but there may be a scenario where duplicate strings have to store against unique values like ID's then how can we do this? If we use ID's as keys then how hash map will efficiently will return the ID bu inputting a value(string)??
     
    princebadshah, Mar 5, 2009
    #16
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Vince Darley
    Replies:
    4
    Views:
    4,466
    emilchacko
    Mar 2, 2010
  2. Timo Nentwig

    byte[] array as HashMap key?

    Timo Nentwig, Mar 8, 2005, in forum: Java
    Replies:
    1
    Views:
    8,589
    Kevin McMurtrie
    Mar 9, 2005
  3. Andrew E

    HashMap with primitive int key

    Andrew E, Nov 28, 2005, in forum: Java
    Replies:
    11
    Views:
    38,054
    Roedy Green
    Nov 30, 2005
  4. Rakesh
    Replies:
    10
    Views:
    12,205
    Mike Schilling
    Apr 8, 2008
  5. M P
    Replies:
    1
    Views:
    500
Loading...

Share This Page