• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

keys vs. values

 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In HashMap and other classes and in general, what is the difference between keys and values?
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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" )
 
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic