Friday 4 November 2022

Get an iterator from array in Java

Define a method that takes an array as input and return an iterator to traverse the elements.

 

Signature

public static <T> Iterator<T> getIterator(T[] array)

Find the below working application.

 


ArrayIterator.java

package com.sample.app.iterators;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ArrayIterator<T> implements Iterator<T>, Iterable<T> {

	private final T[] array;
	private int currentIndex;
	private final int length;

	public ArrayIterator(T[] array) {
		if (array == null) {
			throw new IllegalArgumentException("Array can't be null to get an interator");
		}
		this.array = array;
		currentIndex = 0;
		length = array.length;
	}

	@Override
	public boolean hasNext() {
		return currentIndex < length;
	}

	@Override
	public T next() {
		if (currentIndex >= length) {
			throw new NoSuchElementException();
		}
		return array[currentIndex++];
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

	@Override
	public Iterator<T> iterator() {
		return this;
	}
}

ArrayIteratorDemo.java

package com.sample.app.arrays;

import java.util.Iterator;

import com.sample.app.iterators.ArrayIterator;

public class ArrayIteratorDemo {

	public static <T> Iterator<T> getIterator(T[] array) {
		return new ArrayIterator<T>(array);
	}

	public static void main(String[] args) {
		ArrayIterator<Integer> iterator = (ArrayIterator)getIterator(new Integer[] { 2, 3, 5, 7, 11 });

		for(Integer ele: iterator) {
			System.out.println(ele);
		}
	}

}

Output

2
3
5
7
11



You may like

Interview Questions

Array programs in Java

Generic method to concatenate two arrays in Java

Get the string representation of array by given delimiter in Java

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

No comments:

Post a Comment