Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - pass elements of a list as parameters to an unlimited-arguments method

Tags:

java

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?

like image 464
Aliencc Avatar asked Feb 18 '14 18:02

Aliencc


2 Answers

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]
like image 87
Joshua Taylor Avatar answered Oct 19 '22 11:10

Joshua Taylor


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());
like image 6
rgettman Avatar answered Oct 19 '22 10:10

rgettman