package net.abhinavsarkar.algorist; public class GrowableArray { private Object[] store; public GrowableArray(int initialCapacity) { if (initialCapacity <= 0) { throw new IllegalArgumentException("capacity too small"); } this.store = new Object[initialCapacity]; } public T get(int index) { if (index < 0) { throw new IllegalArgumentException("index too small"); } if (index >= store.length) { throw new IllegalArgumentException("index too large"); } return (T) this.store[index]; } public void set(int index, T val) { if (index < 0) { throw new IllegalArgumentException("index too small"); } if (index >= store.length) { int factor = (int) Math.pow(2, Math.ceil(Math.log(index * 1.0 /store.length)/Math.log(2))); Object[] nStore = new Object[store.length * factor]; System.arraycopy(store, 0, nStore, 0, store.length); this.store = nStore; } this.store[index] = val; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < store.length; i++) { T val = (T) this.store[i]; if (val == null) { sb.append(", "); } else { sb.append(val + ", "); } } sb.delete(sb.length()-2, sb.length()); return "[" + sb.toString() + "]"; } public static void main(String[] arg) { GrowableArray array = new GrowableArray<>(2); array.set(0, "a"); array.set(6, "b"); array.set(9, "c"); array.set(7, "x"); System.out.println(array); System.out.println(array.get(0)); System.out.println(array.get(1)); } }