Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Can we write our own iterator in java?


Asked by Marilyn Lowe on Dec 05, 2021 Java



But we can easily get an iterator over a primitive array in Java using any of the below discussed methods: 1. Writing our own Iterator. Naive solution is write our own Iterator. We just need to override two abstract methods of the Iterator interface - hasNext() and next(). This can be done as demonstrated below:
Also,
In general, to use an iterator to traverse through the contents of a collection follow these steps: Make a loop to decide the next element availability by calling hasNext () method. Get each element from the collection by using next () method. Here is an example demonstrating Iterator.
In respect to this, You can just create an anonymous instance of the iterator without creating extending Iterator and take advantage of the value of currentSize to verify up to where you can navigate over the array (let's say you created an array with capacity of 10, but you have only 2 elements at 0 and 1).
One may also ask,
To implement an iterable data structure, we need to: Create an Iterator class which implements Iterator interface and corresponding methods. We can generalize the pseudo code as follows:
Subsequently,
If you're using an existing iterable object (say, a LinkedList) from java.util, you'll need to either subclass it and override its iterator function so that you return your own, or provide a means of wrapping a standard iterator in your special Iterator instance (which has the advantage of being more broadly used), etc.