This post will discuss 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. This post 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 the 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. Using Guava Library

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

Download Code

Output:

A
B
C

4. Using 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 the iterator back to the start whenever needed.

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

Download Code

Output:

A
B
C

That’s all about getting an iterator over an object array in Java.