import java.util.ArrayList; import java.util.Iterator; public class ArrayList2d implements Iterable { private ArrayList> array; public ArrayList2d() { array = new ArrayList>(); } /** * ensures a minimum capacity of num rows. Note that this does not guarantee * that there are that many rows. * * @param num */ public void ensureCapacity(int num) { array.ensureCapacity(num); } /** * Ensures that the given row has at least the given capacity. Note that * this method will also ensure that getNumRows() >= row * * @param row * @param num */ public void ensureCapacity(int row, int num) { ensureCapacity(row); while (row < getNumRows()) { array.add(new ArrayList()); } array.get(row).ensureCapacity(num); } /** * Adds an item at the end of the specified row. This will guarantee that at * least row rows exist. */ public void add(int row, E data) { ensureCapacity(row); while (row >= getNumRows()) { array.add(new ArrayList()); } array.get(row).add(data); } public E get(int row, int col) { return array.get(row).get(col); } public ArrayList get(int row) { return array.get(row); } public void set(int row, int col, E data) { array.get(row).set(col, data); } public void remove(int row, int col) { array.get(row).remove(col); } public boolean contains(E data) { for (int i = 0; i < array.size(); i++) { if (array.get(i).contains(data)) { return true; } } return false; } public int getNumRows() { return array.size(); } public int getNumCols(int row) { return array.get(row).size(); } @Override public Iterator iterator() { Iterator it = new Iterator() { private int currentIndex = 0; @Override public boolean hasNext() { return currentIndex < array.size() && array.get(currentIndex) != null; } @Override public E next() { return (E) array.get(currentIndex++); } @Override public void remove() { throw new UnsupportedOperationException(); } }; return it; } }