Skip to content

Instantly share code, notes, and snippets.

@joegaudet
Created June 26, 2018 15:23
Show Gist options
  • Save joegaudet/bd2080ee8a85225441435f5f3f934295 to your computer and use it in GitHub Desktop.
Save joegaudet/bd2080ee8a85225441435f5f3f934295 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class ArrayIterator implements Iterator<T> {
// Set local variables
private T[][] array2D;
private int pos = 0; // The position of our cursor
private List list;// What we are going to return
private int maxIterations;
private boolean shouldRemove;
private final int firstIndex = 0;
// The default constructor
public ArrayIterator(T[][] array2D) {
this.array2D = array2D;
this.shouldRemove = false;
copyArray(Array2D);
}
/**
* Move through array
*/
@Override
public boolean hasNext() {
return pos < maxIterations; // Start at 0 and move up
}
/**
* When called will print all the values in the 2D
* Array
*/
@Override
public Integer next() throws NoSuchElementException {
if (!hasNext()) {
throw new NoSuchElementException();
}
// Get value then remove it from the list
Integer result = (Integer) list.get(firstIndex);
pos++;
shouldRemove = true;
remove();
return result;
}
// Set max iterations
public void setMaxIterations(List list) {
if(list != null) {
maxIterations = list.size();
}
}
// Copy values into the collection while skipping over null values
// with a nested for-loop
private void copyArray(T[][] array) {
list = new ArrayList<T>();
// Loop though all values
for (T[] data : array) {
for (int val : data) {
list.add(val);
}
}
// Set total number of iterations
setMaxIterations(getList());
}
// Remove previous element returned by iterator
public void remove() {
if(shouldRemove) {
list.remove(firstIndex);
shouldRemove = false;
}
}
// Return the list
public List getList() {
return this.list;
}
// Test the code
public static void main(String[] args) {
int[][] array2D = { {1, 2}, {3}, {} , {5, 6}, {}, {7, 8, 9, 10} };
ArrayIterator<Integer> ai = new ArrayIterator<Integer>(array2D);
while(ai.hasNext()) {
System.out.println(ai.next());
}
System.out.println(ai.getList());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment