Improve iterator samples, add explanatory comments (KT-20357)

This commit is contained in:
Ilya Gorbunov
2017-11-15 12:56:40 +03:00
parent 4d13ea89b2
commit dca23e339a
@@ -29,6 +29,7 @@ class Iterators {
add("BLUE")
}
// iterator() extension is called here
for (e in vector.elements()) {
println("The element is $e")
}
@@ -39,12 +40,14 @@ class Iterators {
val mutableList = mutableListOf(1, 2, 3)
val mutableIterator = mutableList.iterator()
if (mutableIterator.hasNext()) {
mutableIterator.next()
mutableIterator.remove()
}
// iterator() extension is called here
for (e in mutableIterator) {
if (e % 2 == 0) {
// we can remove items from the iterator without getting ConcurrentModificationException
// because it's the same iterator that is iterated with for loop
mutableIterator.remove()
}
println("The element is $e")
}
}
@@ -61,10 +64,12 @@ class Iterators {
@Sample
fun forEachIterator() {
val iterator = (1..3).iterator()
// skip an element
if (iterator.hasNext()) {
iterator.next()
}
// do something with the rest of elements
iterator.forEach {
println("The element is $it")
}