Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

keys vs. values

 
Kevin Knowles
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In HashMap and other classes and in general, what is the difference between keys and values?
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A key is something like a postal address and a value like a package that is located there. Using an array you could think of an array index as being a key and whatever is stored at that index as a value. For example:

In the code above, using the array analogy, the key is 1 (the subscript) and the value is 2, so the variable i is set to 2. Here is the way you could do the same thing with a Map:

That code is a lot messier than the first, but it shows the relationship between keys and values. The real power of a Map though is the ability to associate any object key to any object value. For example, say we have a group of students with average grades and we want to associate the student's name with the grade:
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Smalltalk used more the more intuitive name Dictionary instead of the implementation-revealing Hashmap. Given a word you can look up the definition. Given a key you can look up the value.
Definition = Dictionary.lookup( Word )
Value = Hashmap.get( Key )
myCapitolCity = myHashmap.get( "Virginia" )
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A key is something like a postal address and a value like a package that is located there.
thanks michael. i tried to answer this question first but i couldn't come with this example
i like it.
regards
maulin
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic