Chapter 12 |
Map
A map (in Python - dictionary) is an object that stores associations between keys and values (key/value pairs). The keys are like indexes. In Map
, the keys are integers, strings or any type of objects. A map cannot contain duplicate keys. Each key maps to one value. A key and its corresponding value form an entry stored in a map. Maps enable fast retrieval, deletion, and updating of pairs through keys.
One of the most useful map classes is HashMap
.
The following example simulates a telephone book:
Map<String, Integer> telephoneBook = new HashMap<>(); telephoneBook.put( "Peeter Peet" , 5562356 ); telephoneBook.put( "Mari Maasikas" , 53438956 ); System.out.println( "Mari's number is " + telephoneBook.get( "Mari Maasikas" )); |
Note: a map has two generic types in the angle brackets: one for the key (String
) and one for its value (Integer
).
Also note that get
returns the null
value if the map contains no mapping for the key.
Chapter 12 |