Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java หาสับลิสต์ (Sublist) ในลิสต์

การหาสับลิสต์ใน Java List

List ใน Java เป็นคอลเลกชันแบบเรียงลำดับที่อนุญาตให้เก็บและเข้าถึงองค์ประกอบตามลำดับ มีเมธอด subList(int fromIndex, int toIndex) สำหรับดึงส่วนย่อยของลิสต์ (ไม่รวมดัชนี toIndex)

อัลกอริทึม

  1. สร้างลิสต์และเพิ่มข้อมูล
  2. กำหนดดัชนีเริ่มต้น (fromIndex) และดัชนีสิ้นสุด (toIndex)
  3. เรียกใช้ list.subList(fromIndex, toIndex)
  4. แสดงผลลัพธ์

ตัวอย่างที่ 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));