Mutable iterators

The mutable iterator extends from the iterator interface as well. As indicated by its name, this iterator works with mutable lists and can help to remove the underlying item in the list.

Take a look the following diagram of the MutableIterator interface, which inherits the Iterator interface:

This interface provides only one function, which is remove(). This function removes the current element of the list.

The following example removes all items that are equal to 3:

fun mutableIterator(){

val mutableListValues : MutableList<Int> = mutableListOf(1,2,3,4,5)
val mutableIterator : MutableIterator<Int> = mutableListValues.listIterator()

while(mutableIterator.hasNext()) {
if(mutableIterator.next() == 3) {
mutableIterator.remove()
}
}
}

The next() and hasNext() functions are from the iterator interface and the remove() function is from the mutableIterator interface. The iterator removes the element from the list if the underlying element is 3.

If the iterator.hasNext() function returns true, it is necessary to move the iterator onto the target element using the next() function.

Execute the following example:

while(mutableIterator.hasNext()) {
mutableIterator.remove()
}

If the remove() function is called before calling the next() function, Kotlin will throw IllegalStateException.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.104.242