I have a method with unlimited parameters:
void X(Object... values){};
And a unknown list that the user should input.
Now I want to pass all the elements of that list to method X, like
this.X(list.get(0), list.get(1)......);
Can anyone please tell me how to do that?
A method declared as
void X(Object... values){};
is similar to a method declared as
void X(Object[] values){};
and can be called with an Object[]
, though only the first can be called with a variable number of arguments. You can convert your list to an array of using List.toArray(), so that you can call X(list.toArray())
. Here's example code demonstrating:
import java.util.Arrays;
public class VarargsExample {
public static void foo( Object... args ) {
System.out.println( "foo: "+Arrays.toString( args ));
}
public static void bar( Object[] args ) {
System.out.println( "bar: "+Arrays.toString( args ));
}
public static void main(String[] args) {
// only foo can be called with variable arity arguments
foo( 1, 2, 3 );
// bar( 4, 5, 6 ); // won't compile
// both methods can be called with object arrays
foo( new Object[] { 7, 8, 9 } );
bar( new Object[] { 10, 11, 12 } );
// so both can be called with List#toArray results
foo( Arrays.asList( 13, 14, 15 ).toArray() );
bar( Arrays.asList( 16, 17, 18 ).toArray() );
}
}
foo: [1, 2, 3]
foo: [7, 8, 9]
bar: [10, 11, 12]
foo: [13, 14, 15]
bar: [16, 17, 18]
You can pass individual items or an array of items to such a varargs method. Convert your list to an array to pass it in, using the toArray
method:
this.X(list.toArray());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With