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.
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.
Use List. toArray(T[] arr) : yourVarargMethod(yourList.
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));
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