-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathEnhancedFor.java
126 lines (100 loc) · 2.83 KB
/
EnhancedFor.java
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import java.util.Iterator;
class EnhancedFor {
public static void main(String[] args) {
System.out.println("begin");
int[] xs = new int[] {};
print(xs);
xs = new int[] {1};
print(xs);
xs = new int[] {1, 2};
print(xs);
xs = new int[] {1, 2, 3, 4, 5};
print(xs);
label: for (int x : xs) {
while (true) {
if (x < 3)
continue label;
if (x > 3)
break label;
System.out.println(x);
break;
}
}
for (Integer i : new Counter(3)) {
System.out.println(i);
}
for (Object o : new RawCounter()) {
System.out.println(o);
}
for (int i : new Counter(3)) {
for (int j : new Counter(3)) {
System.out.println(i + " " + j);
}
}
for (float i : new Counter5()) {
System.out.println((int) i);
}
}
private static void print(int[] xs) {
System.out.print("xs");
for (int x : xs)
System.out.print(" " + x);
System.out.println();
}
private static class CountIterator implements Iterator<Integer> {
private int count = 0;
private final int total;
public CountIterator(int total) {
this.total = total;
}
public boolean hasNext() {
return count < total;
}
public Integer next() {
return ++count;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
private static class CountIteratorSubclass extends CountIterator {
public CountIteratorSubclass(int total) {
super(total);
}
}
private static class Counter implements Iterable<Integer> {
private final int total;
public Counter(int total) {
this.total = total;
}
public Iterator<Integer> iterator() {
return new CountIteratorSubclass(total);
}
}
private static class Counter5 extends Counter {
public Counter5() {
super(5);
}
}
private static class RawIterator implements Iterator {
private int count = 0;
private final int total;
public RawIterator(int total) {
this.total = total;
}
public boolean hasNext() {
return count < total;
}
public Object next() {
return new Integer(++count);
}
public void remove() {
throw new UnsupportedOperationException();
}
}
private static class RawCounter implements Iterable {
public Iterator iterator() {
return new RawIterator(3);
}
}
}