wood burning stoves 2.0*
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 OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP 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: 39478
    
  28
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: 39478
    
  28
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: 39478
    
  28
You’re welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Traits of Hash key