Is there any particular reason the basic Java iterator was programmed not to have a function like peek(), which would return the next element without advancing the iterator?
Peeking Iterator. Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations. Implement the PeekingIterator class: PeekingIterator(Iterator<int> nums) Initializes the object with the given integer iterator iterator .
An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java.util package.
Methods of Iterator The Iterator interface provides 4 methods that can be used to perform various operations on elements of collections.
Iterator object can be created by calling iterator() method present in Collection interface. Syntax: Iterator itr = c. iterator();
Why doesn't the standard Java iterator have peek()?
Because peek()
is not part of the Iterator design pattern as it is normally described.
Because the vast majority of iterator use-cases don't require it. Forcing all implementations (including a myriad custom / 3rd party classes) to implement an unnecessary method would be a bad idea.
Because the peek()
method has potential impacts on the semantics for iterators of lazy data sources.
Because implementing peek()
affects the efficiency (memory, CPU) of a iterator in some circumstances. Whether you actually use it or not.
Because peek()
would in some obscure circumstances lead to a memory leak.
Because ... KISS.
But ultimately, the real reason is ... because they designed it that way back in the year ~2000. And we weren't in the room when the design debates took place1.
1 - For what it is worth, it seems that most2 other languages have made the same decision for their standard iterator API. Rust seems to be an exception to this; see https://doc.rust-lang.org/std/iter/struct.Peekable.html.
2 - ... based on a highly non-scientific "survey" using Google search.
If you want an iterator abstraction that provides peek()
as well, you can extend the Iterator
interface and implement the iterators for yourself. Indeed an general purpose iterator-with-peek can easily be implemented as a wrapper for a regular Iterator
.
Or look for a 3rd-party API / implementation(s); e.g. Guava, Apache Commons, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With