Reputation: 85
Is there any easy way to pass all the values in a arbitrary length List as parameters to a method. In the following code, for example, I would want the params in method2 to be a sequence of the values residing in the params List (but without the List structure). Because the list is of arbitrary length, I can't just run through a loop and assign each value in the list to a variable, and then pass those variables to method2.
void method1( List<Double> params ){
void method2(params...)
}
Thanks! ~ryan
Upvotes: 0
Views: 1168
Reputation: 11
For method2 to be able to receive a variable number of arguments you need to declare it this way:
void method2(Double ... args)
In this case, args will be a Double[].
What you need to do in method1 is to convert your List to a Double[].
Here's a sample:
public static void main(String[] args) {
List<Double> list = new ArrayList<Double>();
list.add(1.0);
list.add(2.0);
list.add(3.0);
method1(list);
}
public static void method1(List<Double> list) {
method2(list.toArray(new Double[] {}));
}
public static void method2(Double... args) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
Hope this helps!
Upvotes: 1
Reputation: 78649
How about this way?
void method1(Double... params ){
method2(Arrays.asList(params));
}
This would allow you to do things like
method1(1.0);
method1(1.0, 2.0);
method1(1.0, 2.0, 3.0);
method1(1.0, 2.0, 3.0, 4.0);
Upvotes: 0
Reputation: 83577
You can declare
public void method2(Double... doubles) {
}
See the Java varargs documentation for details.
Upvotes: 3