9. 48. 10. To perform some operation on all keys: the keys() or keySet() methods |
|
public Enumeration keys()
public Set keySet()
|
|
The keys() method returns the set of keys as an Enumeration. |
The keySet() method returns the set of keys as a Set object. |
Which you use depends upon what you wish to do with the keys. |
import java.util.Enumeration;
import java.util.Hashtable;
public class MainClass {
public static void main(String[] s) {
Hashtable table = new Hashtable();
table.put("key1", "value1");
table.put("key2", "value2");
table.put("key3", "value3");
Enumeration e = table.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + " : " + table.get(key));
}
System.out.println(table.keySet());
}
}
|
|
key3 : value3
key2 : value2
key1 : value1
[key3, key2, key1] |