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

วิธีสร้าง Unmodifiable Set ใน Java 9

Unmodifiable Set ด้วย Set.of()

Java 9 เพิ่ม Set.of() static factory method สำหรับสร้าง immutable set ได้สะดวก

ลักษณะของ Set ที่สร้างโดย Set.of()

  • Immutable: ไม่ add/remove/replace ได้ (UnsupportedOperationException)
  • Mutable Elements: ถ้า elements mutable อาจดูเหมือนเปลี่ยน
  • No Nulls: ไม่อนุญาต null elements (NullPointerException)
  • No Duplicates: Duplicate elements -> IllegalArgumentException
  • Iteration Order: ไม่ได้รับประกัน (unspecified)

Syntax

Set.of(E... elements)

ตัวอย่าง

import java.util.Set;

public class SetOfMethodTest {
    public static void main(String args[]) {
        Set<String> names = Set.of("Adithya", "Bhavish", "Chaitanya", "Jai");
        System.out.println("Names - " + names);
        names.add("Raja"); // throws UnsupportedOperationException
    }
}

Output

Names - [Bhavish, Adithya, Jai, Chaitanya]
Exception in thread "main" java.lang.UnsupportedOperationException

สรุป

Set.of() ให้ immutable set ที่สร้างง่าย ปลอดภัย และมีประสิทธิภาพ เหมาะสำหรับข้อมูล unique และคงที่