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

การ Shuffle (สุ่มลำดับ) List ใน Java ด้วย Collections.shuffle()

ตัวอย่าง: สุ่มลำดับข้อมูลใน ArrayList

import java.util.*;

public class Demo {
    public static void main(String[] args) {
        ArrayList myList = new ArrayList<>();
        myList.add("Hello");
        myList.add(",");
        myList.add("this");
        myList.add("is");
        myList.add("a");
        myList.add("sample");
        
        System.out.println("The original list is: " + myList);
        Collections.shuffle(myList);
        System.out.println("The shuffled list is: " + myList);
    }
}

ผลลัพธ์ตัวอย่าง

The original list is: [Hello, ,, this, is, a, sample]
The shuffled list is: [a, is, ,, Hello, this, sample]

คำอธิบาย: Collections.shuffle(List list) สุ่มลำดับองค์ประกอบในลิสต์แบบ in-place (เปลี่ยนลิสต์ต้นฉบับ) ใช้ Fisher-Yates shuffle algorithm ให้การกระจายสม่ำเสมอ

รูปแบบอื่นๆ

  • Collections.shuffle(list, Random rnd) - ระบุ Random source เอง (เช่น new Random(seed) เพื่อผลลัพธ์ซ้ำได้)
  • Java 8+: list.sort((a, b) -> random.nextInt()) - ไม่แนะนำ ไม่ได้เป็น uniform shuffle จริง

ข้อสังเกต

  • ทำงานกับ List ที่ implement RandomAccess (เช่น ArrayList) ได้เร็วที่สุด
  • LinkedList จะช้ากว่าเพราะ random access ไม่ได้ O(1)
  • Thread-safe: ไม่ thread-safe ต้อง synchronized เองถ้าใช้หลาย thread