บทนำ
ในบทความนี้ เราจะเรียนรู้วิธีการใช้งาน Collection หลายประเภทใน Java
ตัวอย่างการทำงาน
อินพุทตัวอย่าง:
Input list: [101, 102, 103, 104, 105]
เอาต์พุทที่คาดหวัง:
The list after removing an element: 101 102 103 105
อัลกอริทึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศลิสต์ชื่อ input_collection ขั้นตอนที่ 3 - กำหนดค่า ขั้นตอนที่ 4 - ใช้ฟังก์ชัน remove() ส่งค่า index ของสมาชิกที่ต้องการลบ ขั้นตอนที่ 5 - แสดงผลลัพธ์ ขั้นตอนที่ 6 - จบการทำงาน
ตัวอย่างที่ 1: ใช้ ArrayList
ArrayList สร้างขึ้นพร้อมขนาดเริ่มต้น เมื่อขนาดเกินกว่าที่กำหนด คอลเลกชันจะขยายตัวอัตโนมัติ เมื่อลบออบเจ็กต์ออก อาร์เรย์อาจหดเล็กลงได้
import java.util.*;
public class Demo {
public static void main(String[] args) {
ArrayList input_collection = new ArrayList();
for (int i = 1; i <= 5; i++)
input_collection.add(i + 100);
System.out.println("The list is defined as: " + input_collection);
input_collection.remove(3);
System.out.println("\nThe list after removing an element: ");
for (int i = 0; i < input_collection.size(); i++)
System.out.print(input_collection.get(i) + " ");
}
}
เอาต์พุท
The list is defined as: [101, 102, 103, 104, 105] The list after removing an element: 101 102 103 105
ตัวอย่างที่ 2: ใช้ LinkedList
คลาส java.util.LinkedList ทำงานแบบ doubly-linked list การดำเนินการที่เข้าถึงด้วยดัชนีจะเดินทางผ่านลิสต์จากจุดเริ่มต้นหรือจุดสิ้นสุด ขึ้นอยู่กับจุดใดที่ใกล้กว่า
import java.util.*;
public class Demo {
public static void main(String[] args) {
LinkedList input_collection = new LinkedList();
for (int i = 1; i <= 5; i++)
input_collection.add(i + 100);
System.out.println("The list is defined as: " + input_collection);
input_collection.remove(3);
System.out.println("\nThe list after removing an element");
for (int i = 0; i < input_collection.size(); i++)
System.out.print(input_collection.get(i) + " ");
}
}
เอาต์พุท
The list is defined as: [101, 102, 103, 104, 105] The list after removing an element 101 102 103 105
สรุปความแตกต่าง:
- ArrayList: ใช้ dynamic array เหมาะสำหรับการเข้าถึงแบบสุ่ม (Random access) ด้วยดัชนี
- LinkedList: ใช้ doubly-linked list เหมาะสำหรับการเพิ่ม/ลบข้อมูลบ่อยครั้งที่หัว/ท้ายลิสต์