Iterator over an Object array in Java

In this post, we will see how to get an iterator over an object array in Java. The iterator should be able to iterate over all values in the object array.

 
In the previous post, we have discussed how to get an iterator over a primitive array in Java. In this post, we will discuss how to get an iterator over an array of objects in Java.

 

1. Convert Array to a List

For Wrapper types or arrays with non-primitive types, we can use Arrays.asList() to get a list backed by the array. Then we can simply use iterator() method provided by the List interface to get an iterator over the object array.

 

Download   Run Code

Output:

A
B
C

 

2. Implement our own Iterator

Another solution is to implement our own Iterator. We just need to override two abstract methods of the Iterator interface – hasNext() and next(). This can be done as shown below:

 

Download   Run Code

Output:

A
B
C

 

3. Guava

Guava library Iterators class contains several static utility methods that operate on or return objects of type Iterator. We can use forArray() method that returns an iterator containing the elements of the object array.

 

Download   Run Code

Output:

A
B
C

 

4. Apache Commons Collections

Apache Commons Collections ObjectArrayIterator class provides an Iterator over an array of objects. The advantage of using this method is that it has a reset() method, which can reset of the iterator back to the start, whenever needed.

We can also use ArrayIterator class, but the ObjectArrayIterator will perform better for an object array.

 

Download

Output:

A
B
C

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Leave a Reply

avatar
  Subscribe  
Notify of