如何将 int 数组作为参数传递给构造函数?

How to pass int array as an argument to a constructor?

有人能告诉我是否可以将 int 数组作为参数传递给构造函数吗?

我试过以下方法:

public static void main (String args[]){

    Accumulator[] X = new Accumulator[3];     

}

public Accumulator(int[] X) {
    A= new int[X.length];
    for (int i=0; i<X.length; i++)
        A[i] = X[i];
}

您正在 main 方法中初始化一个大小为 3 的累加器数组。

要将 int 数组传递给 Accumulator 的构造函数,您需要执行如下操作:

public static void main (String args[]){
    int[] someArray = {1,2,3};

    Accumulator accumulator = new Accumulator(someArray);
}

public Accumulator(int[] X) {
    A= new int[X.length];
    for (int i=0; i<X.length; i++)
        A[i] = X[i];
}

尝试这样的事情:

public static void main (String args[]){
    int[] test = new int[3];
    test[0] = 1;
    test[1] = 2;
    test[3] = 3;
    Accumulator X = new Accumulator(test);     

}

public Accumulator(int[] X) {
    A= new int[X.length];
    for (int i=0; i<X.length; i++)
        A[i] = X[i];
}

当然,数组只是 java 中的对象,因此您可以将其作为参数传递。尽管您可以简单地使用:

public Accumulator(int[] X){
     A = X;
}

或者,如果您需要复制数组,请使用

public Accumulator(int[] X){
     A = new int[X.length];

     System.arrayCopy(X , 0 , A , 0 , X.length);
}

出于性能原因。

我看到你有很多答案解释了如何对单个对象执行此操作,而不是对数组执行此操作。所以这里是你如何为数组做的:

public static void main (String args[]){

    int array[] = {1, 2, 3};

    Accumulator[] X = new Accumulator[3];       
    for(Accumulator acc : X) {
        acc = new Accumulator(array);
    }
}

当你创建数组时,元素被初始化为空,所以你在循环中创建对象,你可以在那里使用带有数组参数的构造函数。