We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

How to pass an ArrayList to varargs method

In this article we will see how to pass an arraylist to a method expecting vararg as an method argument.

Suppose we have a method that accepts varargs of type IntegerĀ and calculates the sum of them i.e.

Advertisements

int calculateSum(Integer... nums)
{
	int sum = 0;
	for(int num : nums)
	{
		sum = sum + num;
	}
	return sum;
}

Now we can call this function by passing arguments separately i.e.

calculateSum(1,3,4);

or by passing an array i.e.

Integer []arr ={1,3,5,7,9};
calculateSum(arr);

Now suppose we want to pass an ArrayList to this methodā€™s vararg parameter i.e.

ArrayList<Integer> listofInts = new ArrayList<>();
calculate(listofInts); // Compile Error

It will give compile error because we can not directly pass ArrayList to vararg in method parameter. So, letā€™s see how to do this i.e.

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.

calculateSum(listofInts.toArray(new Integer[0]));

Letā€™s see complete example as follows,

package com.thispointer.varargs.example2;

import java.util.ArrayList;
import java.util.Arrays;

public class Example {

	/*
	 * Accepts variable number of arguments and calculate sum of all the
	 * elements passed.
	 */
	int calculateSum(Integer... nums) {
		int sum = 0;
		for (int num : nums) {
			sum = sum + num;
		}
		return sum;
	}

	public static void main(String[] args) {

		Example ex = new Example();

		Integer[] arr = { 1, 3, 5, 7, 9 };
		ArrayList<Integer> listofInts = new ArrayList<>(Arrays.asList(arr));

		// Compile Error
		// Can not pass arraylist to varargs directly
		// int sum = ex.calculateSum(listofInts);

		// Lets convert the arraylist to array and pass it to
		// function accepting varargs.
		int sum = ex.calculateSum(listofInts.toArray(new Integer[0]));

		System.out.println(sum);

	}

}

Output:

25

Other vararg related articles,

Java vararg Tutorial & Example

12
296.208,20