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
Iteratorand takes anEnumerationin the constructor. It provideshasNext()andnext()methods by delegating to thehasMoreElements()andnextElement()methods ofEnumeration. - remove(): The
Iteratorinterface requires aremove()method, but sinceEnumerationdoes not support removing elements, this method throws anUnsupportedOperationException. - Main Demo: In
main(), we create aVectorand obtain anEnumerationfrom it. We then wrap thisEnumerationwithEnumerationIteratorAdapterto use it as anIterator.
Output
The program will print: