Monday, April 18, 2011

Getting keys from hashtable: Iterating over hashtable

Consider the hashtable:

Hashtable ht = new Hashtable(); 
ht.put("1","One"); 
ht.put("2","Two"); 
ht.put("3","Three");

Now getting the keys set can be got as follows:

As a set
Set st = ht.keySet();
 
    System.out.println("Set created from Hashtable Keys contains :");
    //iterate through the Set of keys
    Iterator itr = st.iterator();
    while(itr.hasNext())
      System.out.println(itr.next());
Note:
Please note that resultant Set object is backed by the Hashtable.
Any key that is removed from Set will also be removed from
original Hashtable object. The same is not the case with the element addition.
Eg.
st.remove("2");

Getting from enum:
Enumeration e = ht.keys();
    while(e.hasMoreElements())
      System.out.println(e.nextElement());
  }


No comments:

Post a Comment

Chitika