OnJava8-Examples/holding/AdapterMethodIdiom.java

41 lines
1.2 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: holding/AdapterMethodIdiom.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
// 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() {
2015-05-05 14:05:39 -07:00
return () -> new Iterator<T>() {
int current = size() - 1;
2015-05-05 11:20:13 -07:00
@Override
2015-05-05 14:05:39 -07:00
public boolean hasNext() { return current > -1; }
@Override
public T next() { return get(current--); }
@Override
public void remove() { // Not implemented
throw new UnsupportedOperationException();
2015-04-20 15:36:01 -07:00
}
};
}
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
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
*///:~