IdentityHashMap
In this chapter you will learn:
Use IdentityHashMap
IdentityHashMap
extends AbstractMap
and
implements the Map
interface.
It uses reference equality (==) instead of object
equality (equals()) when comparing keys and values.
IdentityHashMap
obtains hash codes via System's
static int identityHashCode(Object x)
method instead of via each key's
hashCode()
method.
The hash code for the null reference is zero.
IdentityHashMap
is a generic class that has this declaration:
class IdentityHashMap<K, V>
K
specifies the type of keyV
specifies the type of value.
import java.util.IdentityHashMap;
import java.util.Map;
/* j a va 2 s . c o m*/
public class Main {
public static void main(String[] argv) throws Exception {
Map<Object, Object> objMap = new IdentityHashMap<Object, Object>();
Object o1 = new Integer(123);
Object o2 = new Integer(123);
objMap.put(o1, "first");
objMap.put(o2, "second");
Object v1 = objMap.get(o1); // first
Object v2 = objMap.get(o2); // second
}
}
IdentityHashMap vs HashMap
IdentityHashMap
supports mutable keys.
The mutable keys are objects used as keys and whose hash codes change
when their field values change while in the map.
The following code contrasts IdentityHashMap
with HashMap
in a mutable key context
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
// j av a 2 s. c om
public class Main {
public static void main(String[] args) {
Map<Employee, String> map1 = new IdentityHashMap<Employee, String>();
Map<Employee, String> map2 = new HashMap<Employee, String>();
Employee e1 = new Employee("J", 28);
map1.put(e1, "SALES");
System.out.println(map1);
Employee e2 = new Employee("J", 26);
map2.put(e2, "MGMT");
System.out.println(map2);
System.out.println(map1.containsKey(e1));//true
System.out.println(map2.containsKey(e2));//true
e1.setAge(29);
e2.setAge(27);
System.out.println(map1);
System.out.println(map2);
System.out.println(map1.containsKey(e1));//true
System.out.println(map2.containsKey(e2));//false
}
}
class Employee {
private String name;
private int age;
Employee(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Employee))
return false;
Employee e = (Employee) o;
return e.name.equals(name) && e.age == age;
}
@Override
public int hashCode() {
int hashCode = 19;
hashCode = hashCode * 31 + name.hashCode();
hashCode = hashCode * 31 + age;
return hashCode;
}
void setAge(int age) {
this.age = age;
}
void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name + " " + age;
}
}
Next chapter...
What you will learn in the next chapter:
- How to use SortedMap
- How to get first key from SortedMap
- How to get last key and last key value pair in SortedMap
Home » Java Tutorial » Collections