Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an ArrayList to a varargs method parameter?

People also ask

How do I pass an array to Varargs?

Passing an ArrayList to method expecting vararg as parameter To do this we need to convert our ArrayList to an Array and then pass it to method expecting vararg. We can do this in single line i.e. * elements passed. // function accepting varargs.

Can you pass an ArrayList as a parameter in Java?

If we want to pass an ArrayList as an argument to a function then we can easily do it using the syntax mentioned below. In the code above, we created an ArrayList object named 'list' and then we passed it to a function named modifyList.

How do you pass a list to a variable argument in Java?

Use List. toArray(T[] arr) : yourVarargMethod(yourList.

Can an ArrayList be a parameter?

Class one has an ArrayList as one of its attributes and it calls a void method from class two and passes that ArrayList as a parameter. Now that method initializes another ArrayList and makes it equal to the parameter passed by me and makes changes to that new ArrayList .


Source article: Passing a list as an argument to a vararg method


Use the toArray(T[] arr) method.

.getMap(locations.toArray(new WorldLocation[0]))

Here's a complete example:

public static void method(String... strs) {
    for (String s : strs)
        System.out.println(s);
}

...
    List<String> strs = new ArrayList<String>();
    strs.add("hello");
    strs.add("world");
    
    method(strs.toArray(new String[0]));
    //     ^^^^^^^^^^^^^^^^^^^^^^^^^^^
...

In Java 8:

List<WorldLocation> locations = new ArrayList<>();

.getMap(locations.stream().toArray(WorldLocation[]::new));

A shorter version of the accepted answer using Guava:

.getMap(Iterables.toArray(locations, WorldLocation.class));

can be shortened further by statically importing toArray:

import static com.google.common.collect.toArray;
// ...

    .getMap(toArray(locations, WorldLocation.class));