OnJava8-Examples/containers/AdapterMethodIdiom.java
2015-11-15 15:51:35 -08:00

44 lines
1.3 KiB
Java

// containers/AdapterMethodIdiom.java
// ©2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// The "Adapter Method" idiom uses for-in
// with additional kinds of Iterables.
import java.util.*;
class ReversibleArrayList<T> extends ArrayList<T> {
public ReversibleArrayList(Collection<T> c) { super(c); }
public Iterable<T> reversed() {
return () -> new Iterator<T>() { // <* Describe *>
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<String> 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
*/