Custom Iterator in Java with Example

Through this blog, I will be sharing how can we make a custom iterator in Java. Iterators can come in handy in many situations. An iterator is basically an object which can help us to go over a collection, it can serve as an alternative to foreach loop. So let’s explore more about custom iterators and their functionality.

Custom Iterators are made when we take a class that is implementing iterator and then we override the functions. Majorly we override the hasNext(), next(), and remove() functions.

Let us see the below code example for better understanding.

customiterator.java

Code Explanation:

In the above program, we are taking a class named a custom iterator along with creating an ArrayList by default. The constructor of the class creates an empty ArrayList in which we can insert values. Then we are creating a function named as add through which we will be adding values inside the ArrayList.

Then we are creating a function named as iterator under which we are calling MyIterator class.

The main code is present inside the MyIterator class. The constructor of this class initializes a variable “index” as 0. Then we are creating a hasNext() function, which will be responsible for telling whether we have reached at the end or not. At last, we are creating the next() function, which prints the current element and increases the index by 1.

Testing.java

Output:

Code Explanation:

We have created the tester class to check whether the program written in the customiterator class is correct or not. So we make an object of customiterator class and named it as “obj”, and adds some of the values for testing.

Now we have made the iterator of the object class. It’s time to iterate through the obj using the while loop. Till we have a value iit.hasNext() will return true and then we prints current value using next() function.

This blog shared how we can make custom iterators in java. You can customize the iterator according to your needs but the basics will be the same as shown above. Please feel free to comment below if you are facing difficulties and we will be happy to help you.

Leave a Comment

Your email address will not be published. Required fields are marked *