Arrays in Java can store both primitive types and object references, effective for organizing sequential data.
An array is characterized by clone()
method for duplication and an immutable field length
, which defines its capacity.
Array indexing conventionally begins at $0$:
$$ \text{Element's memory location} = \text{Array's memory location} + \text{Element length} \times \text{No. Element} $$
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");
}
a == b
will check for reference/identity, returns false
a.equals(b)
of Object class will check for reference/identity, returns false
Arrays.toString(array)
System.out.print(Arrays.toString(c));
arr
and arr.toString()
will return the hexadecimal representation of hashcode of the memory addressArrays.sort(array)
Arrays.sort(a);
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();
The above three ways perform Shallow Copy, which means it creates a new instance and copies all the fields of the object to that new instance where both are referencing to the same memory in heap memory.
Arrays of primitive types: copies the value
Arrays of objects references: copies the reference of every single object; modifying a object will affect other arrays
/**
* 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;
}