How to trim out an array of integers in Java?

You can't change the size of an array in Java after it has been created. What you can do however, is to create a new array of the size that you need.

Another important point is that you are creating an array of a primitive: int. Primitives are not objects and you cannot assign the value null to a primitive. You need to create an array of java.lang.Integer if you want to be able to set entries in it to null.

Integer[] numArray = new Integer[N];

Thanks to a Java feature called auto-boxing, almost all code that works with primitive int values, also works with Integer values.

Steps:

  1. Use Integer[] instead of int[]
  2. Calculate the size that you need (count non-null entries in original array)
  3. Allocate a new array of the size that you need
  4. Loop over the old array, and copy every non-null value from it to the new array.

Code:

Integer[] oldArray = ...;

// Step 2
int count = 0;
for (Integer i : oldArray) {
    if (i != null) {
        count++;
    }
}

// Step 3
Integer[] newArray = new Integer[count];

// Step 4
int index = 0;
for (Integer i : oldArray) {
    if (i != null) {
        newArray[index++] = i;
    }
}

I think there is a bit shorter way to do the trimming itself. Whats left is to find the proper index.

You can do:

int someIndex = Arrays.asList(arr).indexOf(null);
arr = Arrays.copyOfRange(arr,0,someIndex);

You surely better of with some more appropriate data structure, for example a list or a set depending on what's your intention with it later. That way you don't even need to create an N sized structure just so you'd have to reduce it anyway. Rather you create an empty list and add the elements that you actually need


You can't trim an array. The fastest approach is just to copy it into a smaller one, using System.arraycopy, which is almost always much faster than a for loop:

int somesize = 5;
int[] numArray = new int[somesize];
//code to populate every other int into the array.
int[] smallerArray = new int[somesize/2];
//copy array into smaller version
System.arraycopy(numArray, 0, smallerArray, 0, somesize / 2);

Tags:

Java

Arrays