I had a question regarding ... parameters in java. Here is the code example
class Foo{
private void m1(Object... params){
//do something with params[0]
//do something with params[1]
//do something with params[2]
//do something with params[3]
}
public void m2(Object... params){
Object additionalParam = new Object();
m1(additionalParam, params);
}
}
class Example{
public void main(String[] args){
Foo f = new Foo();
Object o1 = new Object();
Object o2 = new Object();
Object o3 = new Object();
f.m2(o1, o2, o3);
}
}
Does something like this work? I didn't get a compiler error, but when doing something similar, I had problems when changing the value of one of the objects from m1()
.
SOLUTION: I thought that the array would be flattened, but apparently that doesn't happen.
class Foo{
private void m1(Object... params){
//do something with params[0]
//do something with params[1][0]
//do something with params[1][1]
//do something with params[1][2]
}
public void m2(Object... params){
Object additionalParam = new Object();
m1(additionalParam, params);
}
}
class Example{
public void main(String[] args){
Foo f = new Foo();
Object o1 = new Object();
Object o2 = new Object();
Object o3 = new Object();
f.m2(o1, o2, o3);
}
}
Thanks, Sibbo for your contribution.
You are passing two arguments to m1
. One is an Object
(A), and one an Object[]
(B). To access A, you can use params[0]
, but to access any element i
from B, you need to use params[1][i]
.
So if you expected that the resulting array will be flattened, no, it won't be.
If you want to change the values that are stored in the array you pass in the main
method, just do it like you did in your second example. If you want to do it nicely, use proper types instead of Object
.