//: holding/AdapterMethodIdiom.java // The "Adapter Method" idiom uses foreach // with additional kinds of Iterables. import java.util.*; class ReversibleArrayList extends ArrayList { public ReversibleArrayList(Collection c) { super(c); } public Iterable reversed() { return new Iterable() { @Override public Iterator iterator() { return new Iterator() { int current = size() - 1; @Override public boolean hasNext() { return current > -1; } @Override public T next() { return get(current--); } @Override public void remove() { // Not implemented throw new UnsupportedOperationException(); } }; } }; } } public class AdapterMethodIdiom { public static void main(String[] args) { ReversibleArrayList ral = new ReversibleArrayList<>( Arrays.asList("To be or not to be".split(" "))); // Grabs the ordinary iterator via iterator(): for(String s : ral) System.out.print(s + " "); System.out.println(); // Hand it the Iterable of your choice for(String s : ral.reversed()) System.out.print(s + " "); } } /* Output: To be or not to be be to not or be To *///:~