การหาสับลิสต์ใน Java List
List ใน Java เป็นคอลเลกชันแบบเรียงลำดับที่อนุญาตให้เก็บและเข้าถึงองค์ประกอบตามลำดับ มีเมธอด subList(int fromIndex, int toIndex) สำหรับดึงส่วนย่อยของลิสต์ (ไม่รวมดัชนี toIndex)
อัลกอริทึม
- สร้างลิสต์และเพิ่มข้อมูล
- กำหนดดัชนีเริ่มต้น (fromIndex) และดัชนีสิ้นสุด (toIndex)
- เรียกใช้
list.subList(fromIndex, toIndex) - แสดงผลลัพธ์
ตัวอย่างที่ 1: เขียนใน main โดยตรง
import java.util.LinkedList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
int indexStart = 3;
int indexEnd = 6;
List inputList = new LinkedList<>();
for (int i = 1; i <= 9; i++) {
inputList.add(i + 100); // 101, 102, ..., 109
}
System.out.println("ลิสต์เดิม: " + inputList);
// subList(3, 6) = ดัชนี 3, 4, 5 (ไม่รวม 6)
List subList = inputList.subList(indexStart, indexEnd);
System.out.println("องค์ประกอบจากดัชนี " + indexStart + " ถึง " + (indexEnd - 1) + ": " + subList);
}
}
ผลลัพธ์
ลิสต์เดิม: [101, 102, 103, 104, 105, 106, 107, 108, 109]
องค์ประกอบจากดัชนี 3 ถึง 5: [104, 105, 106]
ตัวอย่างที่ 2: ใช้เมธอดแยก (OOP Style)
import java.util.LinkedList;
import java.util.List;
public class Demo {
static void printSublist(List inputList, int start, int end) {
List subList = inputList.subList(start, end);
System.out.println("องค์ประกอบจากดัชนี " + start + " ถึง " + (end - 1) + ": " + subList);
}
public static void main(String[] args) {
int indexStart = 3;
int indexEnd = 6;
List inputList = new LinkedList<>();
for (int i = 1; i <= 9; i++) {
inputList.add(i + 100);
}
System.out.println("ลิสต์เดิม: " + inputList);
printSublist(inputList, indexStart, indexEnd);
}
}
ข้อสังเกตสำคัญ
- Backed by original list: สับลิสต์ที่ได้จะเชื่อมโยงกับลิสต์ต้นฉบับ การแก้ไขสับลิสต์จะส่งผลต่อลิสต์ต้นฉบับด้วย
- IndexOutOfBoundsException: โยนถ้า fromIndex < 0, toIndex > size, หรือ fromIndex > toIndex
- Structural modifications: หากแก้ไขโครงสร้างลิสต์ต้นฉบับ (add/remove) หลังสร้างสับลิสต์ จะได้
ConcurrentModificationExceptionเมื่อใช้สับลิสต์ toIndexเป็น exclusive (ไม่รวม)
การสร้างสำเนาแท้ (Independent Copy)
// สร้างลิสต์ใหม่ที่ไม่เชื่อมโยงกับต้นฉบับ
List independentCopy = new ArrayList<>(inputList.subList(3, 6));