EN
Java - wrap array with Iterable interface
7 points
In this short article, we would like to show how to wrap an array with Iterable
interface in Java.
Presented approach let's to use Iterable
interface on array.
Quick solution:
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.Iterator;
3
4
public class Program {
5
6
public static void main(String[] args) {
7
8
Integer[] array = new Integer[] {1, 2, 3};
9
10
Iterable<Integer> iterable = Arrays.asList(array); // it wraps array with iterable object
11
Iterator<Integer> iterator = iterable.iterator(); // iterator access current array state
12
13
// iterable object only wrapped array, so iterator.next() will return: 4, 5 and 6
14
array[0] = 4;
15
array[1] = 5;
16
array[2] = 6;
17
18
while (iterator.hasNext()) {
19
System.out.println(iterator.next());
20
}
21
}
22
}
Output:
xxxxxxxxxx
1
4
2
5
3
6