In Java, an ArrayList is a commonly used data structure that allows dynamic resizing of an array.
It is a part of the Java Collections framework and provides methods to add, remove, and modify elements in the list.
Passing an ArrayList as a function argument allows the function to manipulate the contents of the list.
To pass an ArrayList as an argument in Java, we can simply declare the function with the ArrayList parameter type.
Here is an example Java program that demonstrates how to pass an ArrayList as a function argument:
import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(20); list.add(30); System.out.println("Original ArrayList: " + list); modifyList(list); System.out.println("Modified ArrayList: " + list); } public static void modifyList(ArrayList<Integer> list) { for(int i = 0; i < list.size(); i++) { list.set(i, list.get(i) * 2); } } }
In this example, we create an ArrayList list
with three integer elements and then print the original contents of the list.
We then call the modifyList
function, passing the ArrayList list
as an argument.
The modifyList
function takes an ArrayList list
as an argument and multiplies each element in the list by 2.
The function does this using a for loop and the set
and get
methods of the ArrayList class.
After calling the modifyList
function, we print the modified contents of the ArrayList.
In conclusion, passing an ArrayList as a function argument in Java is a simple and effective way to manipulate the contents of the list within the function.
By declaring the function with an ArrayList parameter type, we can modify the list in place and avoid the need for global variables.