Java 程序将 ArrayList 作为函数参数传递


在本文中,我们将了解如何将 ArrayList 作为函数参数传递。ArrayList 类是一种可调整大小的数组,可以在 java.util 包中找到它。Java 中的内置数组和 ArrayList 之间存在一个区别,即数组的大小无法修改。

以下对其做出了演示,内容如下 −

假设我们的输入是

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

在此,我们迭代一个字符串数组列表。

Open Compiler
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); } }

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

The required packages have been imported

The list is defined as:
Java Python Scala Mysql Redshift

示例 2

在此,我们迭代一个整型数组列表。

Open Compiler
import java.util.ArrayList; public class Demo { public static void print(ArrayList<Integer> input_list) { System.out.print("\nThe list is defined as:\n "); for(Integer elements : input_list) { System.out.print(elements + " "); } } public static void main(String[] args) { System.out.println("The required packages have been imported"); ArrayList<Integer> input_list = new ArrayList<>(); input_list.add(500); input_list.add(600); input_list.add(700); input_list.add(800); input_list.add(950); print(input_list); } }

输出

The required packages have been imported
The list is defined as:
500 600 700 800 950

更新日期:2022-3-30

超过 4K 的浏览量

开启你的 职业生涯

完成课程以获得认证

开始
广告