Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Java Program to Pass ArrayList as the function argument
The ArrayList is a resizable array, which is part of java.util package. The difference between a built-in array and an ArrayList in Java is that the size of an array cannot be modified.
In this article, we will understand how to pass an ArrayList as a function argument.
Following are the ways to pass an ArrayList as a function argument:
Using Function Argument
We can pass an ArrayList as a function argument in Java. The function can take an ArrayList as a parameter and perform operations on it.
Example
In the following example, we will create an ArrayList of integers and then pass it as a function argument to calculate the sum of its elements.
import java.util.ArrayList;
import java.util.List;
public class ArrayListFunctionArgument {
public static void main(String[] args){
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("Numbers List: " + numbers);
int sum = calculateSum(numbers);
System.out.println("Sum of elements: " + sum);
}
public static int calculateSum(List<Integer> list) {
int sum = 0;
for (int number : list) {
sum += number;
}
return sum;
}
}
Following is the output of the above code:
Numbers List: [1, 2, 3, 4] Sum of elements: 10
Using Return Type
We will create a function that returns an ArrayList. The function can perform operations on the ArrayList and return it.
Example
In the following example, we will create a function that returns an ArrayList of integers. We will then call this function and print the returned ArrayList.
import java.util.ArrayList;
import java.util.List;
public class ArrayListReturnType {
public static void main(String[] args) {
List<Integer> numbers = getNumbers();
System.out.println("Returned Numbers List: " + numbers);
}
public static List<Integer> getNumbers() {
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(10);
list.add(15);
return list;
}
}
Following is the output of the above code:
Returned Numbers List: [5, 10, 15]
