Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty an array in Java / processing

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)?

like image 998
ina Avatar asked Nov 17 '10 20:11

ina


People also ask

How do you clear an entire array in Java?

Using ArrayList To remove an element from an array, we first convert the array to an ArrayList and then use the 'remove' method of ArrayList to remove the element at a particular index. Once removed, we convert the ArrayList back to the array.

How do you destroy an array in Java?

Use List. clear() method to empty an array.

Can you empty an array?

The second way to empty an array is to set its length to zero: a. length = 0; The length property is read/write property of an Array object.

How do you empty an element in an array?

We can use an array instance's filter method to remove empty elements from an array. To remove all the null or undefined elements from an array, we can write: const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ]; const filtered = array.


2 Answers

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.

like image 77
Mark Peters Avatar answered Sep 28 '22 02:09

Mark Peters


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.

like image 22
jjnguy Avatar answered Sep 28 '22 04:09

jjnguy