将值从较大的数组复制到 Java 中的较小的数组

Copy values from a larger size array to a smaller size array in Java

我有一个包含这些值的数组:{0, 1, 3, 2, 3, 0, 3, 1}

我想调用一个 static void remove() 函数,从原始数组中删除所有 #3 值。我创建了一个新数组,数组大小更小,适合我需要复制的数字。我遍历两个数组以复制非#3 值,但继续获取 ArrayIndexOutOfBoundsException,其中 last destination index 6 out of bounds for int[5]

我相信这个逻辑是正确的,本质上,如何将值从较大的数组复制到较小的数组?我是否缺少另一个数组来复制值?

import java.util.Arrays;

public class Main {
    public static int[] remove(int v, int[] in) {
        int size = 0;
        for (int i=0; i<in.length; i++) {
            if (in[i] != v) {
                size++;
            }
        }
        int[] pushArray = new int[size];
        for (int j=0; j<pushArray.length; j++) {
            for (int i=0; i<in.length; i++) {
                if (in[i] == v) {
                    continue;
                } else {
                    System.arraycopy(in, in[i], pushArray, pushArray[i], pushArray.length);
                }
            }
        }
        return pushArray;
    }
    
    public static void main(String args[]) {
        System.out.println("Values from array: ");
        int[] intArray = new int[] {0, 1, 3, 2, 3, 0, 3, 1};
        System.out.println(Arrays.toString(intArray));
        
        int v = 3;
        
        System.out.println("Removing all values of " + v + " from array above ^");
        
        int[] newArray = remove(v, intArray);
        System.out.println(Arrays.toString(newArray));
    }
}

System.arraycopy 不会将元素从一个数组复制到另一个数组,它

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.

表示它从源数组中复制连续的元素,从 srcPos 开始,并按照它们所在的顺序将它们放入目标数组中,从 destPos 开始。

您可以通过简单地将 pushArray[j] 的值设置为 in[i] 来完成您想要做的事情,而无需嵌套循环:

public static int[] remove(int v, int[] in) {
    int size = 0;
    for (int i = 0; i < in.length; i++) {
        if (in[i] != v) {
            size++;
        }
    }
    int[] pushArray = new int[size];

    int j = 0;
    for (int i = 0; i < in.length; i++) {
        if (in[i] != v) {
            pushArray[j++] = in[i];
        }
    }
    return pushArray;
}

输出:

Values from array: 
[0, 1, 3, 2, 3, 0, 3, 1]
Removing all values of 3 from array above ^
[0, 1, 2, 0, 1]

试试这个。

public static int[] remove(int v, int[] in) {
    return IntStream.of(in)
        .filter(i -> i != v)
        .toArray();
}

public static void main(String[] args) {
    int[] in = {0, 1, 3, 2, 3, 0, 3, 1};
    int[] out = remove(3, in);
    System.out.println(Arrays.toString(out));
}

输出:

[0, 1, 2, 0, 1]