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) 
	System.out.println(string);

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;
		@Override
		public boolean hasNext() {
			return data != null && this.position < data.length;
		}
 
		@Override
		public T next() {
			return data[position++];
		}
 
		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}		
	}
 
	private final T[] data;
 
	public IterableArray(T[] data) {
		this.data = data;
	}
 
	@Override
	public Iterator<T> iterator() {
		return new ArrayIteratorImpl();
	}	
}

No comments yet

Post a Comment

Your email is never published. We need your name and email address only for verifying a legitimate comment. For more information, a copy of your saved data or a request to delete any data under this address, please send a short notice to michael@simons.ac from the address you used to comment on this entry.
By entering and submitting a comment, wether with or without name or email address, you'll agree that all data you have entered including your IP address will be checked and stored for a limited time by Automattic Inc., 60 29th Street #343, San Francisco, CA 94110-4929, USA. only for the purpose of avoiding spam. You can deny further storage of your data by sending an email to support@wordpress.com, with subject “Deletion of Data stored by Akismet”.
Required fields are marked *