A HashTable is a collection of key-value pairs. The object to be used as a key should implement the hashCode
and equals
method, and the key and the value should not be null
.
You can read more about the difference between
HashTable
andHashMap
here.
elements()
method in Hashtable
?The elements()
method can be used to get all the values of the HashTable
as an Enumeration
object.
public Enumeration<V> elements()
This method doesn’t take any arguments.
The elements()
method will return an Enumeration
of the values of the HashTable
.
The example below shows how to use the elements()
method.
import java.util.Hashtable;import java.util.Enumeration;class HashtableElementsExample {public static void main( String args[] ) {Hashtable<Integer, String> map = new Hashtable<>();map.put(1, "one");map.put(2, "two");System.out.println("The map is :" + map );Enumeration<String> elements = map.elements();System.out.print("The values are : ");while(elements.hasMoreElements()) {System.out.print(elements.nextElement() + ",");}}}
In the code above:
In line 1, we import the HashTable
class.
In line 6, we create a HashTable
object with the name map
.
In lines 7 and 8, we use the put()
method to add two mappings ({1=one, 2=two}
) to the map
object.
In line 12, we get the values present in the HashTable
using the elements()
method and store them in the elements
variable. Then, we print the elements
object by using the while
loop, hasMoreElements, and nextElement methods.