Java Enumeration Interface with Example - BEHIND JAVA

Java Enumeration Interface with Example

Share This

Enumeration example in java will explain how to use Enumeration with collections. Enumeration is interface and found in java.util package.

This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes such as Vector and Properties, is used by several other API classes, and is currently in widespread use in application code.

Methods in Enumeration Interface

Enumeration interface mainly consist of two methods which are.

boolean hasMoreElements( ) - When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated.

Object nextElement( ) - When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated.

Example of Enumeration

public class EnumerationExample {
public static void main(String[] args) {
 Enumeration number;
 Vector numberVector = new Vector();
 numberVector.add(1);
 numberVector.add(2);
 numberVector.add(3);
 numberVector.add(4);
 numberVector.add(5);
 numberVector.add(6);
 numberVector.add(7);
 numberVector.add(8);
 numberVector.add(9);
 numberVector.add(10);
 number= numberVector.elements();
 while(number.hasMoreElements()){
  System.out.println(number.nextElement());
 }
}

}

Difference between Itrator and Enumeration

Iterators differ from enumerations in two ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.

Below table shows description of methods in itrator and enumeration interfaces

Enumeration Iterator
hasMoreElement() hasNext()
nextElement() next()
NA remove()

Also Iterators are fail-fast . i.e. when one thread changes the collection by add / remove operations , while another thread is traversing it through an Iterator using hasNext() or next() method, the iterator fails quickly by throwing ConcurrentModificationException . The fail-fast behavior of iterators can be used only to detect bugs. The Enumerations returned by the methods of classes like Hashtable, Vector are not fail-fast that is achieved by synchronizing the block of code inside the nextElement() method that locks the current Vector object which costs lots of time.

No comments:

Post a Comment

Pages