21 Sept 2012

HashMap in java Example

HashMap implements Map and extends AbstractMap. It keeps the data in the key and value form. An object of HashMap does not allow key values as duplicates. We can not determine in which order HashMap object displays the data. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator.
 
The following constructors are defined:
HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)
 
The first form constructs a default hash map.
The second form initializes the hash map by using the elements of m. The third form initializes the capacity of the hash map to capacity. The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments.

HashMap doesnot have iterator method. So use the entrySet() method to get the data in Set object form.

import java.util.*;

public class hashmap {
        public static void main(String[] args) {
                HashMap hash = new HashMap();
                hash.put("roll", new Integer(10));
                hash.put("name", "Sathya");
                hash.put("age", 22);
                Set s = hash.entrySet();
                Iterator i = s.iterator();
                while (i.hasNext()) {
                System.out.println(i.next());
                }
        }
}

Output:
roll=10 age=22 name=Sathya

0 comments:

Post a Comment