2015-09-07 11:44:36 -06:00
|
|
|
// containers/AdapterMethodIdiom.java
|
2015-11-11 20:20:04 -08:00
|
|
|
// The "Adapter Method" idiom uses for-in
|
2015-06-15 17:47:35 -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() {
|
2015-11-03 12:00:44 -08:00
|
|
|
return () -> new Iterator<T>() { // <* Describe *>
|
2015-06-15 17:47:35 -07:00
|
|
|
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 + " ");
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
To be or not to be
|
|
|
|
be to not or be To
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|