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

ประโยชน์ของ Immutable Collections ใน Java 9

Factory Methods สำหรับ Immutable Collections

Java 9 เพิ่ม static factory methods ให้ Collections API: List.of(), Set.of(), Map.of(), Map.ofEntries() สร้าง immutable collections ได้ง่ายและกระชับ

ประโยชน์หลัก

  • Less Heap Space: ใช้หน่วยความจำน้อยกว่าแบบดั้งเดิมมาก
  • Faster Access: ลด overhead การ wrap ด้วย Collections.unmodifiable -> เข้าถึงข้อมูลเร็วขึ้น
  • Thread Safety: Immutable collections เป็น thread-safe โดยธรรมชาติ ทุก thread เห็นข้อมูลเหมือนกัน

Syntax

List.of(elements...)
Set.of(elements...)
Map.of(k1, v1, k2, v2)
Map.ofEntries(entry(k1, v1), entry(k2, v2), ...)

ตัวอย่าง

import java.util.Set;
import java.util.List;
import java.util.Map;

public class ImmutableCollectionsTest {
    public static void main(String args[]) {
        List<String> stringList = List.of("a", "b", "c");
        System.out.println("List values: " + stringList);
        
        Set<String> stringSet = Set.of("a", "b", "c");
        System.out.println("Set values: " + stringSet);
        
        Map<String, Integer> stringMap = Map.of("a", 1, "b", 2, "c", 3);
        System.out.println("Map values: " + stringMap);
    }
}

Output

List values: [a, b, c]
Set values: [a, b, c]
Map values: {a=1, b=2, c=3}

ข้อจำกัด

  • ไม่สามารถ add, remove, replace elements ได้ (UnsupportedOperationException)
  • ไม่รับ null elements/keys/values (NullPointerException)
  • Set/Map ไม่รับ duplicate keys/elements (IllegalArgumentException)
  • Iteration order ของ Map/Set ไม่ได้รับประกัน

สรุป

Immutable collections ใน Java 9 ให้ความสะดวก ประสิทธิภาพ และความปลอดภัยสำหรับข้อมูลที่ไม่ต้องเปลี่ยนแปลง