-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAdapterMethodIdiom.java
More file actions
60 lines (47 loc) · 1.44 KB
/
AdapterMethodIdiom.java
File metadata and controls
60 lines (47 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package holding;
/**
* RUN:
* javac holding/AdapterMethodIdiom.java && java holding.AdapterMethodIdiom
* OUTPUT:
* To be or not to be
* be to not or be To
*/
import java.util.*;
public class AdapterMethodIdiom {
public static void main(String[] args) {
ReversibleArrayList<String> ral = new ReversibleArrayList<String>(Arrays.asList("To be or not to be".split(" ")));
// using direct iterator
for (String s : ral) {
System.out.print(s + " ");
}
System.out.println();
// using reversed iterator
for (String s : ral.reversed()) {
System.out.print(s + " ");
}
System.out.println();
}
}
class ReversibleArrayList<T> extends ArrayList<T> {
public 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;
public boolean hasNext() {
return current > -1;
}
public T next() {
return get(current--);
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}