/** * Append-only linear-access data structure containing integers. Designed for * high efficiency and lots of data. (Backed by an array of arrays.) * * Not natively thread-safe. * * @author timmc */ public class IntegerStack { private final int chunkSize; private int[][] data = new int[0][]; private int count = 0; /** * Create an integer stack with the given chunkSize. * @param chunkSize Length of int arrays. */ public IntegerStack(int chunkSize) { this.chunkSize = chunkSize; extend(); } /** * Create an integer stack with the default chunk size (just under * 32 kibi-ints). */ public IntegerStack() { this(1024*32-10); } /** * Grow the major array by one. (Use only when no room left in last minor.) */ private void extend() { int[][] longer = new int[data.length+1][]; System.arraycopy(data, 0, longer, 0, data.length); longer[longer.length-1] = new int[chunkSize]; data = longer; } /** * Add an integer to the end of the list. */ public void add(int val) { if(count % chunkSize == 0) { extend(); } data[count / chunkSize][count % chunkSize] = val; count++; } /** * Create an iterator over this data structure. * @return Fresh iterator. */ public Iterator iterator() { return new Iterator(); } /** * Test functionality. */ public static void main(String[] args) { IntegerStack subject = new IntegerStack(3); int count = 10000; for(int i=0; i