Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the standard Java iterator have peek()?

Tags:

java

iterator

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?

like image 335
La-comadreja Avatar asked Aug 30 '18 23:08

La-comadreja


People also ask

What is peeking 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 .

What is special in iterator in Java?

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.

How many iterator methods are there in Java?

Methods of Iterator The Iterator interface provides 4 methods that can be used to perform various operations on elements of collections.

What is the syntax of iterator in Java?

Iterator object can be created by calling iterator() method present in Collection interface. Syntax: Iterator itr = c. iterator();


1 Answers

Why doesn't the standard Java iterator have peek()?

  1. Because peek() is not part of the Iterator design pattern as it is normally described.

  2. 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.

  3. Because the peek() method has potential impacts on the semantics for iterators of lazy data sources.

  4. Because implementing peek() affects the efficiency (memory, CPU) of a iterator in some circumstances. Whether you actually use it or not.

  5. Because peek() would in some obscure circumstances lead to a memory leak.

  6. 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.

like image 51
Stephen C Avatar answered Sep 28 '22 04:09

Stephen C