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