Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Java Program to Pass ArrayList เป็นอาร์กิวเมนต์ของฟังก์ชัน


ในบทความนี้ เราจะเข้าใจวิธีการส่ง ArrayList เป็นอาร์กิวเมนต์ของฟังก์ชัน ArrayListclass เป็นอาร์เรย์ที่ปรับขนาดได้ ซึ่งสามารถพบได้ในแพ็คเกจ java.util ความแตกต่างระหว่าง abuilt-in array และ ArrayList ใน Java คือขนาดของอาร์เรย์ไม่สามารถแก้ไขได้

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

สมมติว่าข้อมูลที่เราป้อนคือ

Run the program

ผลลัพธ์ที่ต้องการจะเป็น

The list is defined as:
Java Python Scala Mysql Redshift

อัลกอริทึม

Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 - Create an ArrayList, and iterate over it, and display it.
Step 5 - In the main method, create the ArrayList, and add elements to it using the ‘add’ method.
Step 6 - Display this on the console.
Step 7 - Stop

ตัวอย่างที่ 1

ในที่นี้ เราทำซ้ำรายการอาร์เรย์สตริง

import java.util.ArrayList;
public class Demo {
   public static void print(ArrayList<String> input_list) {
      System.out.print("\nThe list is defined as:\n ");
      for(String language : input_list) {
         System.out.print(language + " ");
      }
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      ArrayList<String> input_list = new ArrayList<>();
      input_list.add("Java");
      input_list.add("Python");
      input_list.add("Scala");
      input_list.add("Mysql");
      input_list.add("Redshift");
      print(input_list);
   }
}

ผลลัพธ์

The required packages have been imported

The list is defined as:
Java Python Scala Mysql Redshift

ตัวอย่างที่ 2

ในที่นี้ เราวนซ้ำรายการอาร์เรย์จำนวนเต็ม

import java.util.ArrayList;
public class Demo {
   public static void print(ArrayList<String> input_list) {
      System.out.print("\nThe list is defined as:\n ");
      for(String language : input_list) {
         System.out.print(language + " ");
      }
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      ArrayList<String> input_list = new ArrayList<>();
      input_list.add("Java");
      input_list.add("Python");
      input_list.add("Scala");
      input_list.add("Mysql");
      input_list.add("Redshift");
      print(input_list);
   }
}

ผลลัพธ์

The required packages have been imported

The list is defined as:
Java Python Scala Mysql Redshift