public class CollectionNestIterator {
public static void main(String[] args) {
Collection<Integer> left = new ArrayList<>(Arrays.asList(1,2,3,4,5));
Collection<Integer> right = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7));
for (Iterator<Integer> l = left.iterator(); l.hasNext();) {
for (Iterator<Integer> r = right.iterator(); r.hasNext();) {
System.out.println(l.next() * r.next());
}
}
}
}
Exception in thread "main"
1
4
9
16
25
Disconnected from the target VM, address: '127.0.0.1:2482', transport: 'socket'
java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:854)
at com.insight.cloudeureka.CollectionNestIterator.main(CollectionNestIterator.java:16)
修改:
public class CollectionNestIterator {
public static void main(String[] args) {
Collection<Integer> left = new ArrayList<>(Arrays.asList(1,2,3,4,5));
Collection<Integer> right = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7));
for (Iterator<Integer> l = left.iterator(); l.hasNext();) {
// 增加中间变量
Integer tmp = l.next();
for (Iterator<Integer> r = right.iterator(); r.hasNext();) {
System.out.println(tmp * r.next());
}
}
}
}
1
2
3
4
5
6
7
2
4
6
8
10
12
14
3
6
9
12
15
18
21
4
8
12
16
20
24
28
5
10
15
20
25
30
35
Disconnected from the target VM, address: '127.0.0.1:13010', transport: 'socket'Process finished with exit code 0