Empty an array in Java / processing
Solution 1:
There's
Arrays.fill(myArray, null);
Not that it does anything different than you'd do on your own (it just loops through every element and sets it to null). It's not native in that it's pure Java code that performs this, but it is a library function if maybe that's what you meant.
This of course doesn't allow you to resize the array (to zero), if that's what you meant by
"empty". Array sizes are fixed, so if you want the "new" array to have different dimensions you're 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.
Solution 2:
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, don't 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.
Solution 3:
array = new String[array.length];
Solution 4:
Take double array as an example, if the initial input values
array is not empty, the following code snippet is superior to traditional direct for-loop
in time complexity:
public static void resetValues(double[] values) {
int len = values.length;
if (len > 0) {
values[0] = 0.0;
}
for (int i = 1; i < len; i += i) {
System.arraycopy(values, 0, values, i, ((len - i) < i) ? (len - i) : i);
}
}