forked from Apress/functional-interfaces-in-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestMyInts.java
More file actions
63 lines (57 loc) · 1.33 KB
/
TestMyInts.java
File metadata and controls
63 lines (57 loc) · 1.33 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
61
62
63
package chapter8;
import java.util.*;
import java.util.function.*;
class MyInts implements Iterable<Integer>
{
private int[] array;
public MyInts(int... a)
{
array = Arrays.copyOf(a,a.length);
}
public PrimitiveIterator<Integer,IntConsumer> iterator()
{
return new IntIter();
}
private class IntIter implements
PrimitiveIterator<Integer,IntConsumer>
{
private int cursor;
public IntIter()
{
cursor = 0;
}
@Override
public void forEachRemaining(IntConsumer c)
{
while (hasNext())
{
c.accept(array[cursor]);
cursor++;
}
}
@Override
public boolean hasNext() { return cursor < array.length; }
@Override
public Integer next()
{
int i = 0;
if (hasNext())
{
i = array[cursor];
cursor++;
}
return i;
}
}
}
public class TestMyInts
{
public static void main(String[] args)
{
MyInts my = new MyInts(1, 2, 3, 4, 5);
my.forEach(x -> System.out.println(x));
System.out.println();
my.iterator().forEachRemaining((IntConsumer)x ->
System.out.println(x));
}
}