Java 程序初始化列表
javacampus interviewserver side programmingprogramming更新于 2024/8/8 20:57:00
在本文中,我们将了解如何初始化列表。列表是一个有序集合,允许我们按顺序存储和访问元素。它包含基于索引的方法来插入、更新、删除和搜索元素。它也可以有重复的元素。
下面是相同的演示 −
假设我们的输入是 −
Run the program
期望的输出将是 −
Initializing an integer list The elements of the integer list are: [25, 60] Initializing a string list The elements of the string list are: [Java, Program]
算法
步骤 1 - 开始 步骤 2 - 声明一个整数列表,即 integer_list 和一个字符串列表,即 string_list 步骤 3 - 定义值。 步骤 4 - 使用 List<Integer> integer_list = new ArrayList<Integer>() 初始化整数列表。 步骤 5 - 使用 List<String> string_list = new ArrayList<String>() 初始化整数列表。 步骤 6 - 使用函数 .add() 将项目添加到列表中。 步骤 7 - 显示结果 步骤 8 - 停止
示例 1
在这里,我们将所有操作都绑定在‘main’函数下。
import java.util.*; public class Demo { public static void main(String args[]) { System.out.println("Required packages have been imported"); System.out.println("\nInitializing an integer list"); List<Integer> integer_list = new ArrayList<Integer>(); integer_list.add(25); integer_list.add(60); System.out.println("The elements of the integer list are: " + integer_list.toString()); System.out.println("\nInitializing a string list"); List<String> string_list = new ArrayList<String>(); string_list.add("Java"); string_list.add("Program"); System.out.println("The elements of the string list are: " + string_list.toString()); } }
输出
Required packages have been imported Initializing an integer list The elements of the integer list are: [25, 60] Initializing a string list The elements of the string list are: [Java, Program]
示例 2
在这里,我们将操作封装成展现面向对象编程的函数。
import java.util.*; public class Demo { static void initialize_int_list(){ List<Integer> integer_list = new ArrayList<Integer>(); integer_list.add(25); integer_list.add(60); System.out.println("The elements of the integer list are: " + integer_list.toString()); } static void initialize_string_list(){ List<String> string_list = new ArrayList<String>(); string_list.add("Java"); string_list.add("Program"); System.out.println("The elements of the string list are: " + string_list.toString()); } public static void main(String args[]) { System.out.println("Required packages have been imported"); System.out.println("\nInitializing an integer list"); initialize_int_list(); System.out.println("\nInitializing a string list"); initialize_string_list(); } }
输出
Required packages have been imported Initializing an integer list The elements of the integer list are: [25, 60] Initializing a string list The elements of the string list are: [Java, Program]