How to prune out an integer array in Java?
My number is 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 the loop Therefore, after the for loop, I want to trim (or resize) the array so that there are no more empty slots in the array
Example:
Assume n = 5; This means that every other number from 1 to 5 will be in the array as follows:
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 null index will disappear, and then the array should be:
int arr[0]=1; int arr[1]=3;
The size of the array is now 2
Solution
After creation, you cannot change the size of the array in Java
Another important point is that you are creating an array of primitives: int. primitives are not objects, and you cannot assign the value null to primitives If you want to be able to set the entry to null, you need to create a Java Lang. integer array
Integer[] numArray = new Integer[N];
This is a Java function called auto boxing. Almost all code that uses the original int value is also applicable to integer value
pace:
>Use integer [] instead of int [] > calculate the required size (calculate non null entries in the original array) > allocate a new array of the required size > traverse the old array and copy each non null value into 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; } }