108. Changing array size

Increasing the size of an array is not straightforward. This is because Java arrays are of a fixed size and we cannot modify their size. The solution to this problem entails creating a new array of the requisite size and copying all the values from the original array to this one. This can be done via the Arrays.copyOf() method or via System.arraycopy() (used internally by Arrays.copyOf()).

For an array of primitives (for example, int), we can add the value to an array after increasing its size by 1 as follows:

public static int[] add(int[] arr, int item) {

int[] newArr = Arrays.copyOf(arr, arr.length + 1);
newArr[newArr.length - 1] = item;

return newArr;
}

Or, we can remove the last value as follows:

public static int[] remove(int[] arr) {

int[] newArr = Arrays.copyOf(arr, arr.length - 1);

return newArr;
}

Alternatively, we can resize the array with the given length as follows:

public static int[] resize(int[] arr, int length) {

int[] newArr = Arrays.copyOf(arr, arr.length + length);

return newArr;
}

The code bundled to this book also contains the System.arraycopy() alternatives. Moreover, it contains the implementations for generic arrays. The signatures are as follows:

public static <T> T[] addObject(T[] arr, T item);
public static <T> T[] removeObject(T[] arr);
public static <T> T[] resize(T[] arr, int length);

Being in a favorable context, let's bring a related topic into the discussion: how to create a generic array in Java. The following will not work:

T[] arr = new T[arr_size]; // causes generic array creation error

There are several approaches, but Java uses the following code in copyOf(T[] original, int newLength):

// newType is original.getClass()
T[] copy = ((Object) newType == (Object) Object[].class) ?
(T[]) new Object[newLength] :
(T[]) Array.newInstance(newType.getComponentType(), newLength);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.41.205