I have a List<Thing>
and I would like to pass it to a method declared doIt(final Thing... things)
. Is there a way to do that?
The code looks something like this:
public doIt(final Thing... things) { // things get done here } List<Thing> things = /* initialized with all my things */; doIt(things);
That code obviously doesn't work because doIt()
takes Thing
not List<Thing>
.
Is there a way to pass in a List as the varargs?
This is in an Android App, but I don't see why the solution will not apply to anything Java
If you're passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.
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.
Rules for varargs:There can be only one variable argument in the method. Variable argument (varargs) must be the last argument.
Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String. format . The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.
Java: Passing a list as argument to a vararg method. Use List.toArray (T [] arr): yourVarargMethod (yourList.toArray (new String [0])); (Replace String with whatever type of objects your list contains.)
As you can see, varargs can be really useful in some situations. However, if you are certain about the number of arguments passed to a method, used method overloading instead. For example, if you are certain that sumNumber() method will be used only to calculate the sum of either 2 or 3 arguments,...
Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. accessModifier methodName (datatype… arg) { // method body } In order to define vararg, ... (three dots) is used in the formal parameter of a method.
Also, the compiler may think, you are trying to call test (int n, int ... vargs) with argument passed to the first parameter with empty second parameter. Since there are two possibilities, it causes ambiguity. Because of this, sometimes you may need to use two different method names instead of overloading the varargs method.
Just pass things.toArray(new Thing[things.size()])
.
The variadic argument is internally interpreted as an array. So you should convert it into an array beforehands. Also in your doIt
method you should access things-s elements with array indexing.
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