Java Reference
In-Depth Information
// Print the details
printDetails(map);
}
public static void printDetails(Map<String,String> map) {
// Get the value for the "Donna" key
String donnaPhone = map.get("Donna");
// Print details
System.out.println("Map: " + map);
System.out.println("Map Size: " + map.size());
System.out.println("Map is empty: " + map.isEmpty());
System.out.println("Map contains Donna key: " + map.containsKey("Donna"));
System.out.println("Donna Phone: " + donnaPhone);
System.out.println("Donna key is removed: " + map.remove("Donna"));
}
}
Map: {Donna=(205)678-9823, Ken=(205)678-9823, John=(342)113-9878, Richard=(245)890-9045}
Map Size: 4
Map is empty: false
Map contains Donna key: true
Donna Phone: (205)678-9823
Donna key is removed: (205)678-9823
Removed all entries from the map.
Map: {}
Map Size: 0
Map is empty: true
Map contains Donna key: false
Donna Phone: null
Donna key is removed: null
The
WeakHashMap
class is another implementation for the
Map
interface. As the name of the class implies,
it contains
weak keys
. When there is no reference to the key except in the map, keys are candidates for garbage
collection. If a key is garbage collected, its associated entry is removed from the
Map
. You use a
WeakHashMap
as
implementation class for a
Map
when you want to maintain a cache of key-value pairs and you do not mind if your
key-value pairs are removed from the
Map
by the garbage collector. The
WeakHashMap
implementation allows a
null
key and multiple
null
values. Please refer to Chapter 11 for a complete example of using the
WeakHashMap
class.
Sometimes you want to iterate over keys, values, or entries of a
Map
. The
keySet()
,
values()
and
entrySet()
methods of a map returns a
Set
of keys, a
Collection
of values, and a
Set
of entries, respectively. Iterating over
elements of a
Set
or a
Collection
is the same as described in the “Traversing Collections” section.
The following snippet of code shows how to print all keys of a map:
Map<String,String> map = new HashMap<>();
map.put("John", "(342)113-9878");
map.put("Richard", "(245)890-9045");
map.put("Donna", "(205)678-9823");
map.put("Ken", "(205)678-9823");