2015-12-15 11:47:04 -08:00
|
|
|
// collections/AdapterMethodIdiom.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-11-11 20:20:04 -08:00
|
|
|
// The "Adapter Method" idiom uses for-in
|
2016-01-25 18:05:55 -08:00
|
|
|
// with additional kinds of Iterables
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
class ReversibleArrayList<T> extends ArrayList<T> {
|
2017-05-01 14:33:10 -06:00
|
|
|
ReversibleArrayList(Collection<T> c) {
|
2016-01-25 18:05:55 -08:00
|
|
|
super(c);
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
public Iterable<T> reversed() {
|
2015-12-15 11:47:04 -08:00
|
|
|
return new Iterable<T>() {
|
|
|
|
public Iterator<T> iterator() {
|
|
|
|
return new Iterator<T>() {
|
|
|
|
int current = size() - 1;
|
2016-01-25 18:05:55 -08:00
|
|
|
public boolean hasNext() {
|
|
|
|
return current > -1;
|
|
|
|
}
|
2015-12-15 11:47:04 -08:00
|
|
|
public T next() { return get(current--); }
|
|
|
|
public void remove() { // Not implemented
|
|
|
|
throw new UnsupportedOperationException();
|
|
|
|
}
|
|
|
|
};
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class AdapterMethodIdiom {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
ReversibleArrayList<String> ral =
|
2015-12-15 11:47:04 -08:00
|
|
|
new ReversibleArrayList<String>(
|
2015-06-15 17:47:35 -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 + " ");
|
|
|
|
}
|
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
|
|
|
*/
|