The Adapter Pattern is useful for making two incompatible interfaces compatible by creating a wrapper class (adapter) that allows one interface to be used as another. In this case, the problem requires creating an adapter to allow an Enumeration
to be used as an Iterator
.
Here's a well-organized Java program that implements the Adapter pattern, providing a class that adapts an Enumeration
to an Iterator
.
Solution Code
Explanation
- EnumerationIteratorAdapter: This adapter class implements
Iterator
and takes anEnumeration
in the constructor. It provideshasNext()
andnext()
methods by delegating to thehasMoreElements()
andnextElement()
methods ofEnumeration
. - remove(): The
Iterator
interface requires aremove()
method, but sinceEnumeration
does not support removing elements, this method throws anUnsupportedOperationException
. - Main Demo: In
main()
, we create aVector
and obtain anEnumeration
from it. We then wrap thisEnumeration
withEnumerationIteratorAdapter
to use it as anIterator
.
Output
The program will print: