Algorithm
-
Import Statements:
- Import the necessary classes for ArrayList.
-
Function Definition:
- Define a function that takes an ArrayList as an argument.
-
Inside the Function:
- Process the ArrayList as needed.
-
Main Method:
- Create an ArrayList.
- Add elements to the ArrayList.
- Call the function and pass the ArrayList as an argument.
Code Examples
#1 Code Example- Pass ArrayList as Function Parameter
Code -
Java Programming
import java.util.ArrayList;
class Main {
public static void display(ArrayList < String> languages) {
System.out.print("ArrayList: ");
for(String language : languages) {
System.out.print(language + ", ");
}
}
public static void main(String[] args) {
// create an arraylist
ArrayList < String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
// passing arraylist as function parameter
display(languages);
}
}
Copy The Code &
Try With Live Editor
Output
ArrayList: Java, Python, JavaScript,
#2 Code Example- Pass ArrayList as Function Parameter by converting into Array
Code -
Java Programming
import java.util.ArrayList;
class Main {
public static void percentage(Integer[] marks) {
int totalMarks = 300;
int obtainedMarks = 0;
for(int mark : marks) {
obtainedMarks += mark;
}
// compute average
double percent = (obtainedMarks * 100) / totalMarks;
System.out.println("Percentage: " + percent);
}
public static void main(String[] args) {
// create an arraylist
ArrayList < Integer> marks = new ArrayList<>();
marks.add(67);
marks.add(87);
marks.add(56);
System.out.println("Marks: " + marks);
// passing arraylist as function parameter
percentage(marks.toArray(new Integer[marks.size()]));
}
}
Copy The Code &
Try With Live Editor
Output
Marks: [67, 87, 56]
Percentage: 70.0
Percentage: 70.0
Demonstration
Java Programing Example to Pass ArrayList as the function argument-DevsEnv