Java Reference
In-Depth Information
A program that demonstrates the HashMap<K,V> class is given in Display 16.11 .
This is a variant of Programming Project 15.8 from Chapter 15. In this example, the
program uses the name instance variable as the key to map to an Employee object as
defined in Display 7.2 . Several sample Employee objects are created and added to the
map using the first name as the key. The user is given the opportunity to type in names
until enter is pressed on a blank line. Any name that exists in the map is retrieved and
its information is output to the screen.
Display 16.11
HashMap<K,V> Class Demo (part 1 of 2)
1 // This class uses the Employee class defined in Chapter 7.
2 import java.util.HashMap;
3 import java.util.Scanner;
4 public class HashMapDemo
5 {
6 public static void main(String[] args)
7 {
8 // First create a hashmap with an initial size of 10 and
9 // the default load factor
10 HashMap<String,Employee> employees =
11
new HashMap<String,Employee>(10);
12 // Add several employees objects to the map using
13 // their name as the key
14 employees.put("Joe",
15 new Employee("Joe",new Date("September", 15, 1970)));
16 employees.put("Andy",
17 new Employee("Andy",new Date("August", 22, 1971)));
18 employees.put("Greg",
19 new Employee("Greg",new Date("March", 9, 1972)));
20 employees.put("Kiki",
21 new Employee("Kiki",new Date("October", 8, 1970)));
22 employees.put("Antoinette",
23 new Employee("Antoinette",new Date("May", 2, 1959)));
24 System.out.print("Added Joe, Andy, Greg, Kiki, ");
25 System.out.println("and Antoinette to the map.");
26 // Ask the user to type a name. If found in the map,
27 // print it out.
28 Scanner keyboard = new Scanner(System.in);
29 String name = "";
30 do
31 {
32 System.out.print("\nEnter a name to look up in the map. ");
33 System.out.println("Press enter to quit.");
Search WWH ::




Custom Search