Empty an array in Java / processing

Empty an array in Java / processing

Theres

Arrays.fill(myArray, null);

Not that it does anything different than youd do on your own (it just loops through every element and sets it to null). Its not native in that its pure Java code that performs this, but it is a library function if maybe thats what you meant.

This of course doesnt allow you to resize the array (to zero), if thats what you meant by
empty. Array sizes are fixed, so if you want the new array to have different dimensions youre best to just reassign the reference to a new array as the other answers demonstrate. Better yet, use a List type like an ArrayList which can have variable size.

You can simply assign null to the reference. (This will work for any type of array, not just ints)

int[] arr = new int[]{1, 2, 3, 4};
arr = null;

This will clear out the array. You can also assign a new array to that reference if you like:

int[] arr = new int[]{1, 2, 3, 4};
arr = new int[]{6, 7, 8, 9};

If you are worried about memory leaks, dont be. The garbage collector will clean up any references left by the array.

Another example:

float[] arr = ;// some array that you want to clear
arr = new float[arr.length];

This will create a new float[] initialized to the default value for float.

Empty an array in Java / processing

array = new String[array.length];

Leave a Reply

Your email address will not be published.