62

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

3
  • something like this - float[] xco=new float[1024];
    – ina
    Commented Nov 17, 2010 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. Commented Nov 17, 2010 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
    Commented May 22, 2015 at 15:48

8 Answers 8

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.

10
  • 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
    Commented Aug 30, 2012 at 13:07
  • @jjnguy: I could see an implementation of an array list doing this for the clear operation. Commented Aug 31, 2012 at 18:35
  • Instead of just doing backingStore = new Type[size]?
    – jjnguy
    Commented Aug 31, 2012 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() does: it sets the size to zero and then iterates over the array, zeroing each index. Commented Sep 1, 2012 at 5:05
  • 2
    @IgorGanapolsky: If you have a boolean[] you'd be calling fill(boolean[], boolean), not fill(Object[], Object), and so it would not accept null for the second parameter (as null cannot be assigned to boolean) Commented Oct 1, 2015 at 3:54
43

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.

6
  • 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
    Commented Nov 17, 2010 at 20:10
  • 2
    not so safe since it will break every part of code which uses that array and throw a NullPointerException
    – Jack
    Commented Nov 17, 2010 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
    Commented Nov 17, 2010 at 20:12
  • @ina, or, see my 3rd example.
    – jjnguy
    Commented Nov 17, 2010 at 20:14
  • 2
    I have used arr = new int[]{}; to clear my array instead of making it null. Commented Apr 14, 2018 at 5:37
8
array = new String[array.length];
1
  • 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
    Commented Jun 17, 2020 at 0: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);
  }
}
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];
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);
}
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.

1
  • 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. Commented Nov 17, 2010 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 = [];

Not the answer you're looking for? Browse other questions tagged or ask your own question.