How to cut an array of integers in Java?

Suppose 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 contain any other number from 1 to positive N. This means that the entire array of size N will not be filled after this cycle. So after the for loop, I want to trim (or resize) the array so that there are no more empty slots in the array.

Example:

Let, say, N = 5; This means that after the for loop, 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 indexes that contain zero disappear, and then the array should be:

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

The size of the array is now 2.

+4
source share
4

Java . , .

, : int. , null . java.lang.Integer, null.

Integer[] numArray = new Integer[N];

Java, auto-, , int, Integer.

:

  • Integer[] int[]
  • ( null )
  • null .

:

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

. - , System.arraycopy, , for:

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);
+3

, , - , , , , . , N, .

0

I think there is a slightly shorter way to crop. It remains to find the correct index.

You can do:

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

Source: https://habr.com/ru/post/1533027/


All Articles