Unmodifiable List ด้วย List.of()
Java 9 เพิ่ม List.of() static factory method สำหรับสร้าง immutable list ได้ง่าย
ลักษณะของ List ที่สร้างโดย List.of()
- Immutable: ไม่ add/remove/replace ได้ (UnsupportedOperationException)
- Mutable Elements: ถ้า elements เอง mutable อาจดูเหมือนเปลี่ยน
- No Nulls: ไม่อนุญาต null elements (NullPointerException)
- Serializable: ถ้า elements ทั้งหมด serializable
- Order Preserved: ลำดับเหมือนพารามิเตอร์ที่ส่งเข้า
Syntax
List.of(E... elements)
ตัวอย่าง
import java.util.List;
public class UnmodifiedListTest {
public static void main(String[] args) {
List<String> countries = List.of("India", "Australia", "England", "Newzealand");
System.out.println("Countries - " + countries);
countries.add("Srilanka"); // throws UnsupportedOperationException
}
}
Output
Countries - [India, Australia, England, Newzealand] Exception in thread "main" java.lang.UnsupportedOperationException
สรุป
List.of() เป็นวิธีสร้าง immutable list ที่สะดวกที่สุดใน Java 9+ เหมาะสำหรับข้อมูลคงที่ configuration, constants, lookup tables