Java Program to Pass ArrayList as the function argument
May 31, 2023
What is an ArrayList?
In the Article, we will write a Program to Pass ArrayList as the function argument in java. Arraylists is a part of collection framework in java and is a kind of a resizable array which can be found in the java.util Package. It implements the List interface of the collections framework.
ArrayLists in Java:
In Java, You can store the elements in a dynamic array using the Java ArrayList class of collection Framework. It is Similar to an array, but arraylist has no size restrictions. we can add or remove elements of an arraylist anytime. As a result, it is significantly more adaptable than a conventional array but it may be slower than standard arrays.
Syntax:
ArrayList < > Prep = new ArrayList < > (); // Initialiazation of an ArrayList.
In this program, we first create an ArrayList called list and add some integer values to it. We then call a function called listToArray() and pass the list as a parameter. Inside the listToArray() function, we create an integer array called arr with the same size as the list, using the size() method of the ArrayList. We then use a for loop to iterate over the elements of the list and add them to the corresponding index of the arr using the get() method of the ArrayList. Finally, we return the arr from the function. Back in the main() function, we receive the returned arr and print out the elements of both the list and the arr using for-each loops and System.out.print() statements.
Java Program to Pass ArrayList as Function Parameter:
// Importing all the required packages
import java.util.*;
import java.util.ArrayList;
public class Main{
public static void main(String[] args){
// Initializing the arraylist
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
// Passing arraylist to the function
printList(list);
}
// Function definition
public static void printList(ArrayList list) {
System.out.print("List elements: ");
for(int num : list) {
System.out.print(num + " ");
}
}
}
Output:
List elements: 1 2 3 4 5
In this program, we first create an ArrayList called list and add some integer values to it. We then call a function called printList() and pass the list as a parameter.
Inside the printList() function, we receive the list parameter and use a for-each loop to iterate over the elements of the list and print them out using System.out.print() statements.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment