
1. Overview
In this article, we will learn to convert varargs to List or Array in Java. Varargs introduced in Java 5 and provide a short-hand for methods that support a variable number of parameters of one type.
2. Java convert varargs to Array
The varargs
takes an arbitrary number of values (zero or multiple values as a method parameter). It creates an array automatically and puts the values into the array prior to invoking the method. You must pass multiple arguments in an array or a sequence of arguments, but the varargs feature automates and hides the process.
You can consider the varargs as a simplification of an array.
In the example, the below main method passes a variable number of text values "a"
, "b"
, "c"
(a sequence of arguments) to the foo method. The args
variable argument is assigned directly to String array strArray
.
public static void main(String[] args){ foo("a", "b", "c"); } private static void foo(String...args) { String[] strArray = args; for (int i = 0; i < strArray.length; i++) { System.out.print(strArray[i]); } } /* prints abc */
As mentioned earlier, you can also pass the multiple arguments in an array. For example, the main method passes the strArray
as a variable argument to the foo method.
public static void main(String[] args){ String[] strArray = {"a", "b", "c"}; foo(strArray); } private static void foo(String...args) { String[] strArray = args; for (int i = 0; i < strArray.length; i++) { System.out.print(strArray[i]); } }
3. Java convert varargs to List
To convert the variable argument to a list, you can use Arrays.asList()
method. This method is used to return a fixed-size list backed by the specified array. Since varargs is a simplified form of an array, you can apply the operations that you can perform on an Array to varargs as well.
public static void main(String[] args){ foo("a", "b", "c"); } private static void foo(Object...args) { System.out.println("foo called, args: " + Arrays.asList(args)); } /* prints foo called, args: [a, b, c] */
Alternatively, you can also use Collections.addAll
method to convert a varargs to list.
List<String> list = new ArrayList<>(); Collections.addAll(list, args);
4. Conclusion
To sum up, we have learned to convert varargs to List or Array in Java along with examples.