-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathWrappedIterator.qhelp
More file actions
60 lines (50 loc) · 1.93 KB
/
WrappedIterator.qhelp
File metadata and controls
60 lines (50 loc) · 1.93 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
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<include src="IterableOverview.qhelp" />
<recommendation>
<p>
When writing the <code>iterator()</code> method in an
<code>Iterable<T></code> then it is important to make sure that each call
will result in a fresh <code>Iterator<T></code> instance containing all
the necessary state for keeping track of the iteration. If the iterator is
stored in the <code>Iterable<T></code>, or somehow refers to iteration
state stored in the <code>Iterable<T></code>, then subsequent calls to
<code>iterator()</code> can result in loops that only traverse a subset of the
elements or have no effect at all.
</p>
</recommendation>
<example>
<p>
The following example returns the same iterator on every call, and therefore
causes the second loop to terminate immediately without any effect.
</p>
<sample src="WrappedIteratorBad1.java" />
<p>
This second example returns a newly created iterator each time,
but still relies on iteration state stored
in the surrounding class, and therefore also causes the second loop to
terminate immediately.
</p>
<sample src="WrappedIteratorBad2.java" />
<p>
The code should instead be written like this, such that each call to
<code>iterator()</code> correctly gives a fresh iterator that starts at the
beginning.
</p>
<sample src="WrappedIteratorGood.java" />
</example>
<references>
<li>
The Java Language Specification:
<a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2">The enhanced for statement</a>.
</li>
<li>
The Java API Specification:
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html">Interface Iterable<T></a>,
<a href="https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html">Interface Iterator<T></a>,
<a href="https://docs.oracle.com/javase/8/docs/api/java/nio/file/DirectoryStream.html">Interface DirectoryStream<T></a>.
</li>
</references>
</qhelp>