Search code examples
javadesign-patternsiteratoradapter

Is implementation of Iterator for a specific collection in java is an example of Adapter design pattern?


Is implementation of Iterator for a specific collection is an example of Adapter design pattern ?

For example:- iterator implementation of ArrayList wraps ArrayList adaptee, while iterator implementation of HashSet wraps HashSet adaptee.


Solution

  • No, because all collection implementations in Java should extend java.util.Collection interface which has iterator method. And there is no need to create adapter for collection to get iterator for it.

    But we need to create adapter for other classes which do not implement java.util.Collection or java.lang.Iterable. For example, for well known org.apache.commons.lang3.tuple.Pair class. Below example shows how to create adapter which allow to iterate over it properties like over collection:

    import org.apache.commons.lang3.tuple.ImmutablePair;
    import org.apache.commons.lang3.tuple.Pair;
    
    import java.util.Iterator;
    
    public class DesignPatterns {
    
        public static void main(String[] args) {
            Pair<String, String> pair = new ImmutablePair("A", "B");
            for (String item : new PairIterableAdapter<>(pair)) {
                System.out.println(item);
            }
        }
    }
    
    class PairIterableAdapter<T> implements Iterable<T> {
    
        private final Pair<T, T> pair;
    
        public PairIterableAdapter(Pair<T, T> pair) {
            this.pair = pair;
        }
    
        @Override
        public Iterator<T> iterator() {
            return new Iterator<>() {
                private int counter = 2;
    
                @Override
                public boolean hasNext() {
                    return counter-- > 0;
                }
    
                @Override
                public T next() {
                    switch (counter) {
                        case 1:
                            return pair.getLeft();
                        case 0:
                            return pair.getRight();
                        default:
                            throw new IndexOutOfBoundsException("No more elements!");
                    }
                }
            };
        }
    }
    

    Above code prints:

    A
    B
    

    For collections we do not need to do that because theirs implementation already have iterator() method.

    See also: