void resize() { T[] b = newArray(Math.max(2*n,1)); System.arraycopy(a, 0, b, 0, n); a = b; } void add(int i, T x) { if (i < 0 || i > n) throw new IndexOutOfBoundsException(); if (n + 1 > a.length) resize(); System.arraycopy(a, i, a, i+1, n-i); a[i] = x; n++; } T remove(int i) { if (i < 0 || i > n - 1) throw new IndexOutOfBoundsException(); T x = a[i]; System.arraycopy(a, i+1, a, i, n-i-1); n--; if (a.length >= 3*n) resize(); return x; }
These functions are usually highly optimized and may even use special machine instructions that can do this copying much faster than we could do using a loop. Although using these functions does not asymptotically decrease the running times, it can still be a worthwhile optimization. In the Java implementations here, the use of resulted in speedups of a factor of 2-3 depending on the types of operations performed. Your mileage may vary.
opendatastructures.org