Java Reference
In-Depth Information
The
Map
implementations are
HashMap
,
LinkedHashMap
, and
TreeMap
. Like all the other
Collections Framework classes and interfaces, maps use generics. Maps are different,
though, because you specify two data types when you construct a
Map
object: the data type
of the key and the data type of the value. For example, the declaration of the
TreeMap
class
looks like this:
public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable
The
K
and
V
are generic types for the key and value, respectively. The following
statement declares a new
TreeMap
whose keys are
String
objects and whose values are
Long
objects:
TreeMap<String, Long> phoneBook = new TreeMap<String, Long>();
Unlike
Collection
objects where you “add” an element, with maps you “put” an
element in the map. For example, the following statements put several paired values into
the
phoneBook
map:
phoneBook.put(“Nguyen, Scott”, 2015551111L);
phoneBook.put(“Negreanu, Dan”, 2015552222L);
phoneBook.put(“Ivey, Phil”, 2015553333L);
phoneBook.put(“Rosario, Shirley”, 2015554444L);
phoneBook.put(“Boyd, Russ”, 2015555555L);
The keys in this map are the names and the values are the phone numbers. The
L
after
the phone numbers ensures that the values are autoboxed into
Long
objects. A
TreeMap
orders the elements in the tree based on the natural ordering of the keys, so the elements in
phoneBook
are in alphabetical order.
The
Map
interface contains several methods for obtaining elements. You can obtain
a specifi c value given a key, the entire list of values, and specifi c keys. The following
statements demonstrate some of the
Map
methods. Because of generics, no casting is needed
when you retrieve elements from the map. Study the code and see if you can determine its
result:
14. Long number = phoneBook.get(“Ivey, Phil”); //a value from a key
15. Set<String> keys = phoneBook.keySet();
16. for(String key : keys) {
17. System.out.println(key + “: “ + phoneBook.get(key));
18. }
19.
20. Map.Entry<String, Long> last = phoneBook.lastEntry();
Search WWH ::
Custom Search