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]));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
How do I pass an ArrayList to a method expecting a vararg (Object...)?
Convert your ArrayList into an Array of type object.
ClassName.foo("something", "something", arrayList.toArray());
How to pass a list as parameter for varargs?
Use the List#toArray(T[])
method to create an array from the list, and pass it.
takeParams(strings.toArray(new String[strings.size()]));
How to convert List to varargs object in Java 8
Convert the List<String>
into an array String[]
:
// Java-8(tag in question)
List<Users> users = findByNames(names.toArray(new String[0]));
// Java-11
List<Users> users = findByNames(names.toArray(String[]::new));
Passing a List in as varargs
Just pass things.toArray(new Thing[things.size()])
.
Can I pass an array as arguments to a method with variable arguments in Java?
The underlying type of a variadic method function(Object... args)
is function(Object[] args)
. Sun added varargs in this manner to preserve backwards compatibility.
So you should just be able to prepend extraVar
to args
and call String.format(format, args)
.
Related Topics
How to Instantiate Non Static Inner Class Within a Static Method
What Is the Easiest Way to Parse an Ini File in Java
Jackson Serialization: Ignore Empty Values (Or Null)
Authenticated Http Proxy with Java
Convert from Enum Ordinal to Enum Type
Does a Method's Signature in Java Include Its Return Type
Indexes of All Occurrences of Character in a String
How to Write Custom Exceptions
Setting Property 'Source' to 'Org.Eclipse.Jst.Jee.Server:Jsftut' Did Not Find a Matching Property
Boolean[] VS. Bitset: Which Is More Efficient
What Would an Ast (Abstract Syntax Tree) for an Object-Oriented Programming Language Look Like
Why We Can't Do List<Parent> Mylist = Arraylist<Child>();
Urlconnection Getcontentlength() Is Returning a Negative Value
Android App Bundle Introduces Resource Not Found Crash in Android App