Saturday 5 November 2022

Get reverse iterator for the given array in Java

Write a method that takes an array as input and return the reverse iterator.

 

Signature

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

Define ArrayReverseIterator

 

ArrayReverseIterator.java

package com.sample.app.iterators;

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

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

	private final T[] array;
	private int currentIndex;

	public ArrayReverseIterator(T[] array) {
		if (array == null) {
			throw new IllegalArgumentException("Array can't be null to get an interator");
		}

		this.array = array;
		final int length = array.length;
		currentIndex = length > 0 ? (length - 1) : -1;
	}

	@Override
	public boolean hasNext() {
		return currentIndex > -1;
	}

	@Override
	public T next() {
		if (currentIndex <= -1) {
			throw new NoSuchElementException();
		}
		return array[currentIndex--];
	}

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

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

 

Use ArrayReverseIterator to read the array elements from last.


ArrayReverseIteratorDemo.java

package com.sample.app.arrays;

import java.util.Iterator;

import com.sample.app.iterators.ArrayReverseIterator;

public class ArrayReverseIteratorDemo {

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

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

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

}

 

Output

11
7
5
3
2

 

  

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

Get an iterator from array in Java

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

No comments:

Post a Comment