Algorithm


  1. Import Statements:

    • Import the necessary classes for ArrayList.
  2. Function Definition:

    • Define a function that takes an ArrayList as an argument.
  3. Inside the Function:

    • Process the ArrayList as needed.
  4. 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

x
+
cmd
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

x
+
cmd
Marks: [67, 87, 56]
Percentage: 70.0
Advertisements

Demonstration


Java Programing Example to Pass ArrayList as the function argument-DevsEnv