how to create a WeakHashMap using collections in java
Previous | Home | Next |
In this example we are going to create a WeakHashMap.
For creating a WeakHashMap first of all we have to import the java.util package in which the java.util.WeakHashMap class is contained. In this example we have created a class named the CollectionExample, in which we have created the WeakHashMap and added some elements to it.
In this example we have created a WeakHashMap by using the default constructor of the WeakHashMap class. This is done by the following statement,WeakHashMap<Integer, Integer> whm = new WeakHashMap<Integer, Integer>();
The above statement constructs a new, empty WeakHashMap with the default initial
capacity (16) and the default load factor (0.75).
We have also used the put(Object key, Object value) method for adding the elements to the WeakHashMap. The syntax of put() method is,
put(Object key, Object value)
This method adds the specified value with the specified key in this WeakHashMap.
In this example we have created a class named CollectionExample in which we have created a WeakHashMap whose keys are of Integer type and values are also of Integer type, and by using the put(Object key, Object value) method on its object we have added some elements to it, which is done by the following line in the example,whm.put(1, 1);
where whm is the object of the WeakHashMap which places the integer value 1 corresponding to the key 1.
Finally we have displayed the contents of the WeakHashMap by invoking the iterator on it.
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String args[]) throws IllegalArgumentException, NullPointerException, ClassCastException
{
try
{
WeakHashMap<Integer, Integer> whm = new WeakHashMap<Integer, Integer>();
whm.put(1, 1);
whm.put(2, 2);
whm.put(3, 3);
whm.put(4, 4);
whm.put(5, 5);
System.out.println("The key value pair of the WeakHashMap is given as: ");
Set<Map.Entry<Integer, Integer>> set=whm.entrySet();
Iterator<Map.Entry<Integer, Integer>> itr=set.iterator();
while(itr.hasNext())
{
Map.Entry<Integer, Integer> map=(Map.Entry<Integer, Integer>)itr.next();
System.out.print("Key:= "+map.getKey());
System.out.print(" Value:= "+map.getValue());
System.out.println();
}
}
catch(IllegalArgumentException e)
{
e.printStackTrace();
}
catch(NullPointerException e)
{
e.printStackTrace();
}
catch(ClassCastException e)
{
e.printStackTrace();
}
}
}
The output of the above given example is as follows:
The key value pair of the WeakHashMap is given as:
Key:= 5 Value:= 5
Key:= 4 Value:= 4
Key:= 3 Value:= 3
Key:= 2 Value:= 2
Key:= 1 Value:= 1
Previous | Home | Next |