Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Traits of Hash key

 
Praveen Kumar M K
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You’re welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic