ในบทความนี้ เราจะเข้าใจวิธีการเริ่มต้นรายการ รายการคือคอลเลกชันที่ได้รับคำสั่งซึ่งช่วยให้เราจัดเก็บและเข้าถึงองค์ประกอบตามลำดับได้ ประกอบด้วยวิธีการที่อิงดัชนีเพื่อแทรก อัปเดต ลบและค้นหาองค์ประกอบ นอกจากนี้ยังสามารถมีองค์ประกอบที่ซ้ำกัน
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
สมมติว่าข้อมูลที่เราป้อนคือ −
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
ที่นี่ เราเชื่อมโยงการดำเนินการทั้งหมดเข้าด้วยกันภายใต้ฟังก์ชัน 'หลัก'
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]