1.

Write a program in Java to display the contents of a HashTable using enumeration.

Answer»

We use the hasMoreElements and the nextElement methods of the Enumeration CLASS to ITERATE through the HashMap.

//including the necessary header filesimport java.util.Enumeration;import java.util.Hashtable;public class Iterate_HashTable { public static void main(String[] args) { Hashtable hash_table = new Hashtable();//creating a hash table hash_table.put("1", "Monday"); hash_table.put("2", "Tuesday"); hash_table.put("3", "Wednesday"); hash_table.put("4", "Thursday"); hash_table.put("5", "Friday"); hash_table.put("6", "Saturday"); hash_table.put("7", "Sunday"); Enumeration enumeration_hash_table = hash_table.ELEMENTS();//creating an enumeration object //while loop runs until the hashtable has more entries in it while(enumeration_hash_table.hasMoreElements()) { System.out.println(enumeration_hash_table.nextElement()); } }}

Output:

SaturdayFridayThursdayWednesdayTuesdayMondaySunday

We notice that the order of the values is not the same as that of the order in which we inserted the key-value pair in the hashtable. This is because the elements of a Hashtable are not guaranteed to be in any particular sequence. The hashtable's implementation divides values into multiple buckets based on their Hashcode and internal implementation, which means that the same values may appear in a different order on different machines, runs, or VERSIONS of the framework. This is because Hashtables are designed to retrieve data by key rather than by order.



Discussion

No Comment Found