File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes keys vs. values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "keys vs. values" Watch "keys vs. values" New topic

keys vs. values

Kevin Knowles
Ranch Hand

Joined: Dec 29, 2002
Posts: 45
In HashMap and other classes and in general, what is the difference between keys and values?
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
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:

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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" )

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1873
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.
I agree. Here's the link:
subject: keys vs. values
It's not a secret anymore!