Java Reference
In-Depth Information
Display 16.11
HashMap<K,V>
Class Demo
(part 2 of 2)
34 name = keyboard.nextLine( );
35
if
(employees.containsKey(name))
36 {
37 Employee e = employees.get(name);
38 System.out.println("Name found: " + e.toString( ));
39 }
40
else
if
(!name.equals(""))
41 {
42 System.out.println("Name not found.");
43 }
44 }
while
(!name.equals(""));
45 }
46 }
Sample Dialogue
Added Joe, Andy, Greg, Kiki, and Antoinette to the map.
Enter a name to look up in the map. Press enter to quit.
Joe
Name found: Joe September 15, 1970
Enter a name to look up in the map. Press enter to quit.
Andy
Name found: Andy August 22, 1971
Enter a name to look up in the map. Press enter to quit.
Kiki
Name found: Kiki October 8, 1970
Enter a name to look up in the map. Press enter to quit.
Myla
Name not found.
Self-Test Exercises
6. Can an object that instantiates the
HashMap<K,V>
class contain multiple copies of
some element as a key? How about multiple copies of some element as a value?
7. Suppose that you want a
HashMap<K,V>
that maps a unique employee ID number
to an
Employee
object. Give the definition for a
HashMap<K,V>
variable that
defines and allocates the
HashMap
. You expect to have 100 employees in your
organization. If the employee ID number is an integer between 0 and 100, is a
map a good choice for a data structure to store this information?