2015-04-20 15:36:01 -07:00
|
|
|
//: holding/AdapterMethodIdiom.java
|
2015-04-29 12:53:35 -07:00
|
|
|
// The "Adapter Method" idiom uses foreach
|
2015-04-20 15:36:01 -07:00
|
|
|
// 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 Iterable<T>() {
|
2015-05-05 11:20:13 -07:00
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
public Iterator<T> iterator() {
|
|
|
|
return new Iterator<T>() {
|
|
|
|
int current = size() - 1;
|
2015-05-05 11:20:13 -07:00
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
public boolean hasNext() { return current > -1; }
|
2015-05-05 11:20:13 -07:00
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
public T next() { return get(current--); }
|
2015-05-05 11:20:13 -07:00
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
public void remove() { // Not implemented
|
|
|
|
throw new UnsupportedOperationException();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class AdapterMethodIdiom {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
ReversibleArrayList<String> ral =
|
2015-05-05 11:20:13 -07:00
|
|
|
new ReversibleArrayList<>(
|
2015-04-20 15:36:01 -07:00
|
|
|
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
|
2015-05-05 11:20:13 -07:00
|
|
|
*///:~
|