Java Reference
In-Depth Information
a salary map that associates people's names with their salaries. Notice that we have to
use the wrapper type
Double
rather than the primitive type
double
:
Map<String, Double> salaryMap = new HashMap<String, Double>();
Key/value pairings are added to a map using its
put
method, which is roughly
similar to the
add
method of most other collections. The
put
method accepts a key
and a value as parameters and stores a mapping between the key and value in the
map. If the key was previously associated with some other value, the new association
replaces the old one. We can add key/value pairs to our salary map using code like
the following:
salaryMap.put("Stuart Reges", 10000.00);
salaryMap.put("Marty Stepp", 95500.00);
salaryMap.put("Jenny", 86753.09);
Once you've added key/value pairs to a map, you can look up a value later by call-
ing the map's
get
method, which accepts a key as a parameter and returns the value
associated with that key:
double jenSalary = salaryMap.get("Jenny");
System.out.printf("Jenny's salary is $%.2f\n", jenSalary);
To see whether a map contains a mapping for a given key, you can use the
containsKey
method, or you can call the
get
method and test for a
null
result:
Scanner console = new Scanner(System.in);
System.out.print("Type a person's name: ");
String name = console.nextLine();
// search the map for the given name
if (salaryMap.containsKey(name)) {
double salary = salaryMap.get(name);
System.out.printf("%s's salary is $%.2f\n", name, salary);
} else {
System.out.println("I don't have a record for " + name);
}
Table 11.5 lists several useful
Map
methods.
A
Map
's
toString
method displays a comma-separated list of its key/value pairs.
The order in which the keys appear depends on the type of map used, which we'll
discuss in a moment. Here's what the salary map declared previously would look like
when the program prints it:
{Jenny=86753.09, Stuart Reges=10000.0, Marty Stepp=95500.0}
Search WWH ::
Custom Search