This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Traits of Hash key Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Traits of Hash key" Watch "Traits of Hash key" New topic
Author

Traits of Hash key

Praveen Kumar M K
Ranch Hand

Joined: Jul 03, 2011
Posts: 256
Shorter Version - What are the traits of a HashMap key?

Extended Version - A certain someone asked me a question for which, I frankly had no clue where to start looking for the answer! We know a HashMap is made up of key and value pairs. In most cases I've worked with key being an integer type which suffices for a basic level of uniqueness(so that it'll be easier to use the map as a dictionary). I haven't still read up much on Hashing functions and algorithms so maybe one of you can tell me about this. Am also not sure whether the question meant what kind of data can be put into a HashMap(and what are its traits).

Thanks.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37884
    
  22
Welcome to the Ranch

Not quite. A HashMap hides an array of Map.Entry objects, and each of those contains a reference to a key and a value. It uses the hash code of a key submitted and a sort of remainder operation to get the index in the array to seek its Entry. If the object used as a Key changes its state, and gets a different hash code, the Map will look in a different location in the array, and will probably never find the Entry again.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37884
    
  22
You can use any kind of reference type for the Key and the Value, but it is best only to use immutable types for the Key, otherwise you get the hash code change problem I told you about earlier. String is a common kind of Key.
Praveen Kumar M K
Ranch Hand

Joined: Jul 03, 2011
Posts: 256
Immutable types ha...That does make sense! I can probably research on this line.

And thank you very much for the reply and the warm welcome, Campbell Ritchie

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37884
    
  22
You’re welcome
 
wood burning stoves
 
subject: Traits of Hash key
 
Similar Threads
HashMap's Map.Entry interface
HashMap interview Question.
Searching a JTree
What came first - the chicken or the egg?
Confirmation on HashMap