3. Arrays

Characteristics of Arrays

$$ \text{Element's memory location} = \text{Array's memory location} + \text{Element length} \times \text{No. Element} $$

Static Methods in Arrays Class

java.util.Arrays

Array a and array b are Object instances:

int[] a = {1, 2, 3, 4, 5}; int[] b = {1, 2, 3, 4, 5};

Arrays.equals(array1, array2)

if (Arrays.equals(a, b)) { System.out.println("Arrays with same contents"); }

Arrays.toString(array)

System.out.print(Arrays.toString(c));

Arrays.sort(array)

Arrays.sort(a);

Copying

Arrays.copyOf(srcArr, length);

int[] d = Arrays.copyOf(a, 2); // d = [1, 2] int[] d = Arrays.copyOf(a, 10); // d = [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]

System.arraycopy(srcArr, srcIdx, desArr, desIdx, length);

int[] e = new int[5]; System.arraycopy(a, 0, e, 0, 3); // e = [1, 2, 3, 0, 0]

array.clone()

int[] g = {1, 2, 3, 4, 5}; int[] h = g.clone();

Resizing Array

/** * Remove item at the specified index and return a new array; * If the index is not within bounds, return the array */ public static char[] delete(char[] data, int index) { if (index >= 0 && index < data.length) { char[] tmp = new char[data.length - 1]; System.arraycopy(data, 0, tmp, 0, index); System.arraycopy(data, index + 1, tmp, index, data.length - index - 1); return tmp; } return data; }

Worst-Case Efficiencies of Arrays


Back to Home Next Lecture