How to trim out an array of integers in Java?

Tags: ,



Let’s that I have a number N. N will be the size of the array.

int numArray [] = new numArray[N];

However, the contents of the array will hold every other number from 1 to positive N. This means that the entire size N array will not be full after that for loop. So after the for loop, I want to trim (or resize) the array so that there will no longer be any empty slots in the array.

Example :

Let’s say N = 5; That means, after the for loop, every other number from 1 to 5 will be in the array like so:

int arr[] = new int[N];

int arr[0]=1;
int arr[1]=3;
int arr[2]= null;
int arr[3]= null;
int arr[4]= null;

Now, I want to trim (or resize) after the for loop so that the indexes that hold null will be gone and then the array should be:

int arr[0]=1;
int arr[1]=3;

The size of the array is now 2.

Answer

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;
    }
}


Source: stackoverflow