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).
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.
Joined: Oct 13, 2005
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
Joined: Jul 03, 2011
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