Wednesday 1 April 2020

Pass ArrayList to a method with varargs?

In java, you can create a method that takes variable number of arguments. This feature is called varargs or variable number of arguments. Method which accepts variable number of arguments is called varargs method.

Syntax
returnType methodName(dataType … parameterName){

}

"..." tells the compiler that this is a vararg.

For example, ‘printInfo’ method takes varargs of string as argument and prints.

private static void printInfo(String... data) {
    for (String str : data) {
        System.out.println(str);
    }
}

Since printInfo takes an array as argument, you can convert the list to an array and call this method like below.
printInfo(countries.toArray(new String[countries.size()]));

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.List;

public class App {

    private static void printInfo(String... data) {
        for (String str : data) {
            System.out.println(str);
        }
    }

    public static void main(String args[]) {
        List<String> countries = Arrays.asList("India", "Sri Lanka", "Singapore", "Australia");

        printInfo(countries.toArray(new String[countries.size()]));
    }

}

Output
India
Sri Lanka
Singapore
Australia


You may like

No comments:

Post a Comment