Archives for 

Enumeration in Java

Enumeration in Java

Enumeration in Java

Enumeration is a legacy interface in Java. It is using to iterate elements in legacy collections like Hashtable .This discussion gives a basic overview on enumeration in Java

Enumeraton Vs Iterator

Both are interfaces in Java for iterating data in a collections .Iterator is the improved version of Enumeration.The method names are shorter in case of Iterator.And one remove() method has been added  in Iterator interface.

Methods in Enumeration

1)boolean hasMoreElements()

2)E nextElement()

Methods in Iterator

1) boolean hasNext()

2) E next()

3) void remove()

Iterating Vector using Enumeration

Let us see how the legacy class Vector is iterating using Enumeration.In our example we are storing a number of Strings in our Vector.Then iterating them using an Enumeration object.

Let us verify the output


Added items to vector
Now iterating using Enumeration..

Iterating Hashtable using Enumeration

Now let us see how a Hashtable is iterating using Enumeration. Here ,we are using  Integer objects as keys and String as values.After inserting data as key – value pair, an Enumeration object is using to  get the  key values. Then displaying the value mapped with each key.

Let us see the output.


Added key value pairs
Keys in Enumeration are :
Key = 3
value = dog
Key = 2
value = sheep
Key = 1
value = cow
Key = 0
value = cat

The two examples discussed  above  gives a clear idea about Enumeration interface.

See Related Discussions:

Collections in Java

Iterator in Java

Threading in Java