Reputation: 79
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
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
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
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
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