jeeps95
jeeps95

Reputation: 79

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

Could someone tell me if its possible to pass an int array as an argument to a constructor?

I have tried the following:

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

Upvotes: 1

Views: 16785

Answers (4)

levious
levious

Reputation: 96

I see you got many answers that explain how to do it for a single object, but not for an array. So here's how you can do it for an array:

public static void main (String args[]){

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

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

When you create the array, the elements are initialised to null, so you create the objects in the loop, and you can use the constructor with the array parameter there.

Upvotes: 0

user4668606
user4668606

Reputation:

Sure, an Array is just an Object in java, therefore you can pass it as an argument. Although you could simply use:

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

or, if you need to copy the array, use

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

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

for performance reasons.

Upvotes: 0

brso05
brso05

Reputation: 13222

Try something like this:

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

Upvotes: 1

beresfordt
beresfordt

Reputation: 5222

You are initializing an array of Accumulators with size three in your main method.

To pass an int array to the constructor of Accumulator you would need to do something like the following:

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

Upvotes: 4

Related Questions