How to pass an ArrayList to a varargs method parameter?
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));