Java 程序初始化列表
在本文中,我们将了解如何初始化列表。列表是一种有序集合,允许我们按顺序存储和访问元素。它包含基于索引的方法,用于插入、更新、删除和搜索元素。它还可以包含重复的元素。
以下是同样的演示 −
假设我们的输入是 −
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]
算法
Step 1 - START Step 2 - Declare an integer list namely integer_list and a string list namely string_list Step 3 - Define the values. Step 4 - Use the List<Integer> integer_list = new ArrayList<Integer>() to initialize the integer list. Step 5 - Use List<String> string_list = new ArrayList<String>() to initialize the integer list. Step 6 - Use the function .add() to add items to the list. Step 7 - Display the result Step 8 - Stop
例 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]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP