Java Reference
In-Depth Information
Thesecharacteristicsgive IdentityHashMap aperformanceadvantageoverother
Map implementations.Also, IdentityHashMap supports mutable keys (objectsused
askeysandwhosehashcodeschangewhentheirfieldvalueschangewhileinthemap).
Listing 5-21 contrasts IdentityHashMap with HashMap where mutable keys are
concerned.
Listing 5-21. Contrasting IdentityHashMap with HashMap in a mutable key context
import java.util.IdentityHashMap;
import java.util.HashMap;
import java.util.Map;
class IdentityHashMapDemo
{
public static void main(String[] args)
{
Map<Employee, String> map1 = new IdentityHashMap<>();
Map<Employee, String> map2 = new HashMap<>();
Employee e1 = new Employee("John Doe", 28);
map1.put(e1, "SALES");
System.out.println(map1);
Employee e2 = new Employee("Jane Doe", 26);
map2.put(e2, "MGMT");
System.out.println(map2);
System.out.println("map1
contains
key
e1
=
"+map1.containsKey(e1));
System.out.println("map2
contains
key
e2
=
"+map2.containsKey(e2));
e1.setAge(29);
e2.setAge(27);
System.out.println(map1);
System.out.println(map2);
System.out.println("map1
contains
key
e1
=
"+map1.containsKey(e1));
System.out.println("map2
contains
key
e2
=
"+map2.containsKey(e2));
}
 
Search WWH ::




Custom Search