ede3954d86
See notes in "Foreword to the Leanpub Edition"
51 lines
1.4 KiB
Java
51 lines
1.4 KiB
Java
// collections/AdapterMethodIdiom.java
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
// Visit http://OnJava8.com 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> {
|
|
ReversibleArrayList(Collection<T> c) {
|
|
super(c);
|
|
}
|
|
public Iterable<T> reversed() {
|
|
return new Iterable<T>() {
|
|
public Iterator<T> iterator() {
|
|
return new Iterator<T>() {
|
|
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
|
|
*/
|