Skip to content

Commit caf1fcb

Browse files
authored
Chapter 5: iterator use
1 parent e38e3b7 commit caf1fcb

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

tutorial/05_Collections_Lists.adoc

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
----
3636
public static void foo(Iterable<String> container) {
3737
for (String element: container) {
38-
bar(element)
38+
bar(element);
3939
}
4040
}
4141
----
@@ -59,3 +59,51 @@ public interface Iterator<E> {
5959
void remove(); // Удаляет из коллекции элемент, который вернул последний вызов next
6060
}
6161
----
62+
63+
Порядок ручного использования итератора в общем случае выглядит так:
64+
65+
1. Создать итератор с помощью вызова `iterator()`.
66+
2. Проверить, есть ли следующий элемент `hasNext()`. Если его нет -- перебор закончен.
67+
3. Достать следующий элемент `next()`.
68+
4. Сделать необходимую его обработку. Если для данного элемента это требуется, его можно удалить вызовом метода `remove()`.
69+
5. Вернуться к пункту 2.
70+
71+
Всё то же самое можно выполнить с помощью обычного цикла `for-each`, кроме удаления элемента.
72+
73+
[source,java]
74+
----
75+
public static void foo(Iterable<String> container) {
76+
for (String element: container) {
77+
bar(element);
78+
}
79+
// Is equivalent to
80+
Iterator<String> it = container.iterator();
81+
while (it.hasNext()) {
82+
String element = it.next();
83+
bar(element);
84+
}
85+
}
86+
----
87+
88+
Важно, однако, отметить, что удалить элемент в цикле for-each невозможно. Например:
89+
90+
[source,java]
91+
----
92+
public static void foo(Collection<String> container) {
93+
Iterator<String> it = container.iterator();
94+
while (it.hasNext()) {
95+
String element = it.next();
96+
if (condition(element)) it.remove();
97+
}
98+
// Is NOT equivalent to
99+
for (String element: container) {
100+
if (condition(element)) {
101+
container.remove(element); // Produces ConcurrentModificationException
102+
}
103+
}
104+
// However, it's possible...
105+
container.removeIf(::condition);
106+
}
107+
----
108+
109+

0 commit comments

Comments
 (0)