59

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

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
ina
  • 19,167
  • 39
  • 122
  • 201
  • something like this - `float[] xco=new float[1024];` – ina Nov 17 '10 at 20:11
  • 2
    Java is designed so you don't have to worry about this. You should be able to arrange your code so you don't have to do anything. For the few examples where it might make a difference, they can easily be refactored so this is not needed. – Peter Lawrey Nov 17 '10 at 20:22
  • 1
    The question here is unclear to me. Are you asking 1) how do I set all elements to null in an array or 2) how do I remove all elements from the array. If the elements in the array are no longer desired and what you want is an empty array (i.e., an array with zero elements) ready to be used again then you can use `myArray.clear();` or `myArray = new ArrayList();`. If you want each element in the array to be null for some specific need in your code then this is not an empty array; it is an array of nulls. I down voted this question, but will up vote it if you address my concern. – Jason May 22 '15 at 15:48

8 Answers8

86

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.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
  • There is no reason to loop through an array an `null` out every entry. What do you gain when you do this over simply reassigning a new value to the array? (Sorry for the comment on the old answer.) – jjnguy Aug 30 '12 at 13:07
  • @jjnguy: I could see an implementation of an array list doing this for the clear operation. – Mark Peters Aug 31 '12 at 18:35
  • Instead of just doing `backingStore = new Type[size]`? – jjnguy Aug 31 '12 at 20:13
  • 4
    @jjnguy: Sure. Zeroing the array is a lot more efficient than creating a new one (particularly when the JLS requires the new array to be zeroed out anyway). In fact, this is exactly what OpenJDK's [`ArrayList.clear()`](http://www.docjar.com/html/api/java/util/ArrayList.java.html) does: it sets the size to zero and then iterates over the array, zeroing each index. – Mark Peters Sep 01 '12 at 05:05
  • Interesting. It seems like it would be way less efficient to have to iterate over the entire array. W/e, I'll believe you. I don't have any evidence to support my claim anyway. – jjnguy Sep 01 '12 at 18:54
  • This doesn't compile for me. Error: `Cannot resolve method fill(boolean[], null)` – IgorGanapolsky Sep 30 '15 at 13:50
  • 2
    @IgorGanapolsky: If you have a `boolean[]` you'd be calling [`fill(boolean[], boolean)`](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#fill(boolean[],%20boolean)), not `fill(Object[], Object)`, and so it would not accept `null` for the second parameter (as `null` cannot be assigned to `boolean`) – Mark Peters Oct 01 '15 at 03:54
  • it doesn't have overload for `T[]` – M.kazem Akhgary Nov 25 '18 at 16:37
  • This does not work with char[]. Solution according to oracle: Arrays.fill(myCharArray, '0'); – Anonymous Apr 27 '21 at 09:47
  • @Anonymous: As has been commented elsewhere, this example was for object arrays, and if you have primitives you have to use one of the overloads instead, and choose a default value other than `null`. `'0'` is an odd choice for an "empty" char, probably you meant `0` or `'\0'` – Mark Peters Apr 27 '21 at 14:03
41

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.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
  • 1
    i get the nullpointerexception error when i simply empty an array assigning it to null... the idea is that the same array is reused in each iterations, but the numbers do not matter after each one, so it can be emptied. – ina Nov 17 '10 at 20:10
  • 2
    not so safe since it will break every part of code which uses that array and throw a `NullPointerException` – Jack Nov 17 '10 at 20:12
  • 2
    @ina, if you assign `null` to the array, you will not be able to use it anymore. You will have to redeclare an array into that reference. See my second example. – jjnguy Nov 17 '10 at 20:12
  • @ina, or, see my 3rd example. – jjnguy Nov 17 '10 at 20:14
  • 2
    I have used `arr = new int[]{};` to clear my array instead of making it `null`. – Senura Dissanayake Apr 14 '18 at 05:37
  • this is not really optimal, especially if array is large, allocating new memory for array has some costs. optimal solution is to fill array with zeros. – M.kazem Akhgary Nov 25 '18 at 16:39
8
array = new String[array.length];
Adam
  • 43,763
  • 16
  • 104
  • 144
  • So this will initiated with all the default values right and in this case they are null ? But will this not increase the chances of nullPointerException ? – Mr. Jain Jun 17 '20 at 00:40
5

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);
  }
}
Shiqing Fan
  • 688
  • 2
  • 8
  • 14
4

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];
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
3

Faster clearing than Arrays.fill is with this (From Fast Serialization Lib). I just use arrayCopy (is native) to clear the array:

static Object[] EmptyObjArray = new Object[10000];

public static void clear(Object[] arr) {
    final int arrlen = arr.length;
    clear(arr, arrlen);
}

public static void clear(Object[] arr, int arrlen) {
    int count = 0;
    final int length = EmptyObjArray.length;
    while( arrlen - count > length) {
        System.arraycopy(EmptyObjArray,0,arr,count, length);
        count += length;
    }
    System.arraycopy(EmptyObjArray,0,arr,count, arrlen -count);
}
R.Moeller
  • 3,436
  • 1
  • 17
  • 12
2

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.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
AlexR
  • 114,158
  • 16
  • 130
  • 208
  • This is exactly what `ArrayList` does for you behind the scenes. It works to do it yourself, but is more cumbersome and easy to make mistakes with. IMO, better to use a `Collection` class. But if you're stuck with using an array directly, this is a good observation. – Mark Peters Nov 17 '10 at 21:04
-1

I was able to do that with the following 2 lines, I had an array called selected_items used to get all selected items on a dataTable

selected_items = null;
selected_items = [];
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Cesar Duran
  • 377
  • 3
  • 8