Mutable list iterators

This is the most powerful iterator. The mutable list iterator extends both the list iterator and the MutableListIterator interface, and has its own functions. In the following diagram, we can see how MutableListIterator inherits both MutableIterator and ListIterator:

Let's take a look at the functions provided:

  • add(element): The add function inserts the element in the list. The element will either be inserted before the element that is returned by the next() function or after the element that is returned by the previous() function:
fun mutableListIteratorFunctionAdd() {

val mutableListValues: MutableList<Int> = mutableListOf(2, 3, 6)
var mutableListIterator: MutableListIterator<Int> = mutableListValues.listIterator()

while (mutableListIterator.hasNext()) {
if (mutableListIterator.next() == 3)
mutableListIterator.add((4))
}

println(mutableListValues)
while (mutableListIterator.hasPrevious()) {
if (mutableListIterator.previous() == 6)
mutableListIterator.add((5))
}
println(mutableListValues)
}
  • set(element): The set() function updates the element that is called by next() or previous():
fun mutableListIteratorFunction() {
val mutableListValues: MutableList<Int> = mutableListOf(2, 3, 6)
var mutableListIterator: MutableListIterator<Int> = mutableListValues.listIterator()

println(mutableListValues)

while (mutableListIterator.hasNext()) {
if (mutableListIterator.next() == 3) {
mutableListIterator.set(4)
}
}
println(mutableListValues)
}

Here, the set function has replaced element 3 with element 4.

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

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