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.

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

1 thought on “How to pass an ArrayList to varargs method”

  1. Pingback: Passing Variable Arguments to a function in Java using varargs – Tutorial & Example – thisPointer.com

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top