List iterators

The list iterator extends from the iterator interface and also has some additional functions. While the iterator interface can only move in one direction, the list iterator can move in both directions. It can check the next element with the hasNext() function, and it can also check the previous function with the hasPrevious() function. Take a look at the following diagram of ListIterator, which inherits from the Iterator interface:

Let's have a quick look at all of the provided functions:

  • hasPrevious(): This function returns true if the iterator finds an element at its previous location from its current location. Otherwise, it returns false.
  • previous(): This function returns the previous element from its current location and moves the cursor backward.
  • nextIndex(): Int: This function returns the next index from the current position.
  • previousIndex(): Int: This function returns the previous index from the current position:

Take a look at the following example, where ListIterator is used to iterate over the list, moving forward and backward using the next and previous functions:

fun listIterator() {

val list: List<Int> = listOf(10, 20, 30)
var iteraror: ListIterator<Int> = list.listIterator()

println("has next and next function")
while (iteraror.hasNext()) {
println(iteraror.next())
}
println("has previous and previous function")
while (iteraror.hasPrevious()) {
println(iteraror.previous())
}

println("nextIndex ${iteraror.nextIndex()}")
println("next ${iteraror.next()}")

println("nextIndex ${iteraror.nextIndex()}")
println("next ${iteraror.next()}")

println("previousIndex ${iteraror.previousIndex()}")
println("previous ${iteraror.previous()}")
}

Verify each function of the iterator by looking at the result. 

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

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