An iterable array

January 12, 2010 by Michael

Java has the nice Iterable interface (since Java 5, i guess) that allows object oriented loops like

List<String> strings = new ArrayList<String>();
for(String string : strings) 

but guess what, a simple array is not iterable…

In case you need one, feel free to use this one:

package ac.simons;
import java.util.Iterator;
public class IterableArray<T> implements Iterable<T> {
	private class ArrayIteratorImpl implements Iterator<T> {
		private int position = 0;
		public boolean hasNext() {
			return data != null && this.position < data.length;
		public T next() {
			return data[position++];
		public void remove() {
			throw new UnsupportedOperationException();
	private final T[] data;
	public IterableArray(T[] data) { = data;
	public Iterator<T> iterator() {
		return new ArrayIteratorImpl();

No comments yet

Post a Comment

Your email is never published nor shared. Required fields are marked *