Behavior of the Iterator size method in Scala
source link: https://blog.adamgamboa.dev/behavior-of-the-iterator-size-method-in-scala/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Behavior of the Iterator size method in Scala – Adam Gamboa G – DeveloperSkip to content
Full Stack notes and tips for developers… Java, React, Kubernetes, Scala, and more…
Iterators are a useful structure to iterate over collections (List, Set, Seq, Map, etc) and access their elements one by one. Two important methods in Scala Iterator are next()
and hasNext
.
- hasNext: Indicates if there is another element to return
- next(): Returns that element.
Iterators are mutable things. You can think of them as pointers. Each time you ask an iterator to give you the next element it points to it will move one position further.
Behavior of the size method
When the size of a iterator is requested, it will traverse each element in the sequence it points to, moving each time one position to the right. When it has no more elements to traverse iterator.hasNext == false
it will return the size. But by then it will have exhausted all the elements.
When a new call to size
is made, the iterator is already positioned at the end, so it will immediately return 0. Therefore if you tries to iterate your iterator after getting the size of it, you will notice the iterator is not doing anything.
val list = scala.collection.immutable.List(1, 2, 3) val iterator = list.iterator println(iterator.size) // 3 println(iterator.hasNext) // false println(iterator.size) // 0
val list = scala.collection.immutable.List(1, 2, 3)
val iterator = list.iterator
println(iterator.size) // 3
println(iterator.hasNext) // false
println(iterator.size) // 0
Reference
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK