In this Collection framework tutorial we will learn what is java.util.IdentityHashMap in Collection framework in java.
Contents of page :
- 9.1) Iterate over keys -
- 9.2) Iterate over values -
- 9.3) Iterate over Entry-
1) What is hierarchy of IdentityHashMap in java?
-java.lang.Object
-java.util.AbstractMap
-java.util.IdentityHashMap
For more detailed hierarchy information read : Map hierarchy in java
2) java.util.IdentityHashMap
IdentityHashMap enables us to store data in key-value pair form.
IdentityHashMap when comparing keys (and values) performs reference-equality in place of object-equality. In an IdentityHashMap, two keys k1 and k2 are equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)
Constructs a new IdentityHashMap, with maximum size of 21.
Map<Integer,String> identityHashMap=new IdentityHashMap<Integer,String>();
|
Defining IdentityHashMap<Integer,String> means key can of Integer type and value can be String type only, using any other type will cause compilation error.
4) put element in java.util.IdentityHashMap
put(K key, V value)
Method allows you put specified key-value pair in IdentityHashMap. If the map already contains a mapping for the key, the old value is replaced.
identityHashMap.put(11, "audi");
|
5) get elements from IdentityHashMap
get(Object key)
Method returns value corresponding to key.
Method returns null if map does not contain key.
identityHashMap.get(2);
|
Method returns element on 2nd index.
6) Remove element from IdentityHashMap
remove(Object key)
Method removes key-value pair from IdentityHashMap.
identityHashMap.remove(11);
|
7) contains element in IdentityHashMap
contains(Object object)
Method returns true if IdentityHashMap contains specified on specified index.
identityHashMap.get(2);
|
Method returns element on 2nd index.
8) Size of java.util.IdentityHashMap
size()
Method returns size of IdentityHashMap.
System.out.println(identityHashMap.size());
|
will print size of IdentityHashMap.
9) Iterate over java.util.IdentityHashMap >
Before iterating we will put 3 key-value pairs in IdentityHashMap.
identityHashMap.put(11, "audi");
identityHashMap.put(21, "bmw");
identityHashMap.put(31, "ferrari");
9.1) Iterate over keys -
IdentityHashMap.keySet().iterator() method returns iterator to iterate over keys in IdentityHashMap.
Iterator<Integer> keyIterator=identityHashMap.keySet().iterator();
while(keyIterator.hasNext()){
System.out.println(keyIterator.next());
}
/*OUTPUT
21
11
31
*/
|
Iteration using enhanced for loop.
IdentityHashMap.keySet() returns set of keys.
Set<Integer> keySet=identityHashMap.keySet();
for(Integer key :keySet){
System.out.println(key);
}
|
iterator returned is fail fast. Means any structural modification made to IdentityHashMap like adding or removing elements during Iteration will throw java.util.ConcurrentModificationException.
Iterator<String> iterator=identityHashMap.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
IdentityHashMap.put(4, "d");
}
|
9.2) Iterate over values -
IdentityHashMap.values().iterator() method returns iterator to iterate over keys in IdentityHashMap.
Iterator<String> valueIterator=identityHashMap.values().iterator();
while(valueIterator.hasNext()){
System.out.println(valueIterator.next());
}
/*OUTPUT
bmw
audi
ferrari
*/
|
Iteration using enhanced for loop.
IdentityHashMap.values() returns collection of values.
Collection<String> collection=identityHashMap.values();
for(String value :collection){
System.out.println(value);
}
|
iterator returned is fail fast. Means any structural modification made to IdentityHashMap like adding or removing elements during Iteration will throw java.util.ConcurrentModificationException.
Iterator<String> iterator=identityHashMap.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
IdentityHashMap.put(4, "d");
}
|
9.3) Iterate over Entry-
IdentityHashMap.entrySet().iterator() method returns iterator to iterate over keys in IdentityHashMap.
Iterator<Entry<Integer, String>> entryIterator=identityHashMap.entrySet().iterator();
while(entryIterator.hasNext()){
System.out.println(entryIterator.next());
}
/*OUTPUT
21=bmw
11=audi
31=ferrari
*/
|
Iteration using enhanced for loop.
IdentityHashMap.entrySet() returns collection of values.
Set<Entry<Integer, String>> entrySet=identityHashMap.entrySet();
for(Entry<Integer, String> entry:entrySet){
System.out.println(entry);
}
|
iterator returned is fail fast. Means any structural modification made to IdentityHashMap like adding or removing elements during Iteration will throw java.util.ConcurrentModificationException.
10) Some other important methods of java.util.WeakHashMap
isEmpty() method returns true if this map contains any key-value pair.
clear() method removes all key-value pair from map.
11) synchronizing java.util.IdentityHashMap
We can synchronize IdentityHashMap by using Collections’s class synchronizedList method.
Map synchronizedMap = Collections.synchronizedMap(IdentityHashMap);
|
Now, no 2 threads can access same instance of map concurrently.
12) Complexity of methods in java.util.IdentityHashMap
Operation/ method
|
Worst case
|
Best case
|
put(K key, V value)
|
O(n)
|
O(1)
|
get(Object key)
|
O(n)
|
O(1)
|
13) Features of java.util.IdentityHashMap
- IdentityHashMap enables us to store data in key-value pair form.
- IdentityHashMap is implementation of the java.util.map interface.
- Null elements - One null key can be added. And null values are also allowed.
- Insertion order - Does not maintains insertion order.
Example-
Let’s say we add 3 elements in IdentityHashMap
identityHashMap.put(1,"ind");
identityHashMap.put(2,"aus");
identityHashMap.put(3,"sa");
On displaying insertion order will not be maintained i.e.
3,sa
2,aus
1,ind
|
- synchronized - It is not synchronized (because 2 threads on same IdentityHashMap object can access it at same time).
14) When to use java.util.IdentityHashMap
- While storing key-value we want keys (and values) comparison to be performed on basis of reference-equality in place of object-equality.
- IdentityHashMap can be used when we want to maintain proxy objects. For example, we might need to maintain proxy object for each object debugged in the program.
- IdentityHashMap can be used when we want to store only one null key.
- IdentityHashMap can be used when value corresponding to key might be null.
- IdentityHashMap can be used when we don’t care about insertion order.
- IdentityHashMap can be used when we are not working in multithreading environment.
15) Example/ Program to show comparing keys (and values) performs reference-equality in place of object-equality. In an IdentityHashMap, two keys k1 and k2 are equal if and only if (k1==k2)
import java.util.IdentityHashMap;
import java.util.Map;
public class IdentityHashMapExample {
public static void main(String args[]){
Map<String,String> identityHashMap=new IdentityHashMap<String,String>();
identityHashMap.put(new String("a"), "audi");
identityHashMap.put(new String("a"), "ferrari");
System.out.println(identityHashMap);
}
}
/*OUTPUT
{a=audi, a=ferrari}
*/
|
reference-equality >
new String("a") == new String("a") returns false.
object-equality >
new String("a").equals(new String("a")) returns true.
As IdentityHashMap performs reference-equality two keys gets stored in IdentityHashMap.
16) Example/ Program to show overridden equals() and hashCode() method are not called while storing object in IdentityHashMap -
import java.util.IdentityHashMap;
import java.util.Map;
class Emp{
String name;
Emp(String name){
this.name=name;
}
@Override
public int hashCode(){
System.out.println("in hashCode()");
return (this.name==null ? 0: this.name.hashCode() );
}
@Override
public boolean equals(Object obj){
System.out.println("in equals()");
Emp emp=(Emp)obj;
return (emp.name==this.name || emp.name.equals(this.name));
}
}
public class IdentityHashMapExample {
public static void main(String args[]){
Map<Emp,String> identityHashMap=new IdentityHashMap<Emp,String>();
identityHashMap.put(new Emp("a"), "audi");
identityHashMap.put(new Emp("a"), "bmw");
System.out.println(">>>>>>>>>>>>>> size = "+identityHashMap.size());
System.out.println(">>>>>>>>>>>>>> identityHashMap.get(new Emp(\"a\")) = "+identityHashMap.get(new Emp("a")));
}
}
/*OUTPUT
>>>>>>>>>>>>>> size = 2
>>>>>>>>>>>>>> identityHashMap.get(new Emp("a")) = null
*/
|
So in this Collection framework tutorial we learned what is java.util.IdentityHashMap in Collection framework in java.
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
RELATED LINKS>
ConcurrentHashMap in java - with Segments formation in detail with diagram
WeakHashMap in java
EnumMap in java with program
Basic Collection - All properties in tabular form >
Collection - List, Set and Map all properties in tabular form
Collection hierarchy >
Map hierarchy in java - Detailed - HashMap, Hashtable, ConcurrentHashMap, LinkedHashMap, TreeMap, ConcurrentSkipListMap, IdentityHashMap, WeakHashMap, EnumMap classes
Important Similarity and Differences >
Map Differences >
HashMap and Hashtable - Similarity and Differences
HashMap and ConcurrentHashMap - Similarity and Differences
HashMap vs Hashtable vs LinkedHashMap vs TreeMap - Differences
HashMap vs IdentityHashMap - Similarity and Differences with program
Important Similarity and Differences Collection classes in concurrent and non-concurrent packages >
TreeSet vs ConcurrentSkipListSet - Similarity and Differences with program
TreeMap vs ConcurrentSkipListMap - Similarity and Differences with program
Top Collection Interviews question and answers >
COLLECTION - Top 50 interview questions and answers in java for fresher and experienced
COLLECTION - Top 50 interview questions and answers in java for fresher and experienced
Labels:
Collection Framework
Core Java