Other than looping through each element in an array and setting each one to null, is there a native function in Java / processing to simply empty an array (or destroy it, to
If Array xco
is not final then a simple reassignment would work:
i.e.
xco = new Float[xco .length];
This assumes you need the Array xco
to remain the same size. If that's not necessary then create an empty array:
xco= new Float[0];
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);
}
}
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.
I just want to add something to Mark's comment. If you want to reuse array without additional allocation, just use it again and override existing values with new ones. It will work if you fill the array sequentially. In this case just remember the last initialized element and use array until this index. It is does not matter that there is some garbage in the end of the array.
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.
array = new String[array.length];