Java Reference
In-Depth Information
21. System.out.println(“Last entry = “ + last.getKey()
+ “ “ + last.getValue());
22.
23. String firstKey = phoneBook.firstKey();
24. System.out.println(“First key = “ + firstKey);
A description of the previous statements follows:
1. Line 14 shows how to use the get method to obtain a value given a key. The value of
number is 2015553333 .
2. Line 15 shows how to use the keySet method to obtain a Set of just the keys. The keys
are String objects in phoneBook , as seen by the data type of the keys reference.
3. The for-each loop on line 16 uses the get method to obtain the value, displaying each
key-value pair in phoneBook .
4. Map.Entry is an object for storing map elements. The last reference on line 20 points
to the last map entry in phoneBook , which based on the natural ordering of String
objects is “Rosario, Shirley“ .
5. Line 21 demonstrates the getKey and getValue methods of Map.Entry , which return
“Rosario, Shirley” and 2015554444 , respectively.
6. Line 23 demonstrates the firstKey method, which returns the first key in the set. In
phoneBook , that is “Boyd, Russ“ .
The output of the previous statements is
Boyd, Russ: 2015555555
Ivey, Phil: 2015553333
Negreanu, Dan: 2015552222
Nguyen, Scott: 2015551111
Rosario, Shirley: 2015554444
Last entry = Rosario, Shirley 2015554444
First key = Boyd, Russ
TreeMap is a good choice for a phone book because elements are retrieved and inserted
in log( n ) time, where n is the number of elements. A TreeMap with hundreds of thousands
of entries has a relatively effi cient access time.
The HashMap and LinkedHashMap classes have similar put and get methods for adding
and retrieving elements. Elements in a HashMap are iterated in arbitrary order, while a
LinkedHashMap maintains the elements in their order of insertion. Use a HashMap if ordering
does not matter, a LinkedHashMap if insertion order is suffi cient, and a TreeMap if you need
to control the specifi c ordering of elements.
Search WWH ::




Custom Search