Empty an array in Java / processing

ina picture ina · Nov 17, 2010 · Viewed 290.8k times · Source

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 be able to redeclare it as a new array)?

Answer

Mark Peters picture Mark Peters · Nov 17, 2010

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.