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

วิธี implement Set interface ใน JShell Java 9

JShell เป็นเครื่องมือ command-line ใน Java 9 ใช้รันคำสั่งง่ายๆ เช่น expressions, classes, interfaces, methods เป็นต้น

Set เป็น interface ใน Java ที่กำหนด contract สำหรับ collection ที่มี unique elements ถ้า object1.equals(object2) คืนค่า true แล้วจะมีเพียงหนึ่งใน object1 และ object2 ที่อยู่ใน Set implementation ได้

Snippet 1: Set.of() - Immutable Set

jshell> Set<String> set = Set.of("Adithya", "Chaitanya", "Jai");
set ==> [Jai, Adithya, Chaitanya]

jshell> set.add("Adithya");
|  java.lang.UnsupportedOperationException thrown

jshell> Set<String> hashSet = new HashSet<>(set);
hashSet ==> [Chaitanya, Jai, Adithya]

jshell> hashSet.add("Adithya");
$8 ==> false

jshell> hashSet
hashSet ==> [Chaitanya, Jai, Adithya]

หมายเหตุ: Set.of() คืนค่า immutable set ไม่รองรับ add() จะโยน UnsupportedOperationException ต้องสร้าง HashSet ใหม่จาก Set เดิมจึงจะ add ได้ ผลลัพธ์ false แสดงว่าเพิ่ม "Adithya" ซ้ำไม่ได้

Snippet 2: HashSet - ไม่มีลำดับ

jshell> Set<Integer> numbers = new HashSet<>();
numbers ==> []

jshell> numbers.add(12345);
$11 ==> true

jshell> numbers.add(1234);
$12 ==> true

jshell> numbers.add(123);
$13 ==> true

jshell> numbers.add(12);
$14 ==> true

jshell> numbers
numbers ==> [1234, 12345, 123, 12]

ลำดับ: ไม่มีการจัดเรียง (ไม่ใช่ insertion order และไม่ใช่ sorted order)

Snippet 3: LinkedHashSet - รักษา insertion order

jshell> Set<Integer> numbers1 = new LinkedHashSet<>();
numbers1 ==> []

jshell> numbers1.add(12345);
$17 ==> true

jshell> numbers1.add(1234);
$18 ==> true

jshell> numbers1.add(123);
$19 ==> true

jshell> numbers1.add(12);
$20 ==> true

jshell> numbers1
numbers1 ==> [12345, 1234, 123, 12]

jshell> numbers1.add(123456);
$22 ==> true

jshell> numbers1
numbers1 ==> [12345, 1234, 123, 12, 123456]

ลำดับ: ตาม insertion order (12345 → 1234 → 123 → 12 → 123456)

Snippet 4: TreeSet - เรียงลำดับ sorted order

jshell> Set<Integer> numbers2 = new TreeSet<>();
numbers2 ==> []

jshell> numbers2.add(12345);
$25 ==> true

jshell> numbers2.add(1234);
$26 ==> true

jshell> numbers2.add(123);
$27 ==> true

jshell> numbers2.add(12);
$28 ==> true

jshell> numbers2
numbers2 ==> [12, 123, 1234, 12345]

jshell> numbers2.add(123456);
$30 ==> true

jshell> numbers2
numbers2 ==> [12, 123, 1234, 12345, 123456]

ลำดับ: เรียงจากน้อยไปมาก (natural ordering)

ตารางเปรียบเทียบ Set Implementations

Implementation ลำดับ Performance Null Elements Thread-Safe
HashSet ไม่มีลำดับ O(1) อนุญาต 1 null ไม่
LinkedHashSet Insertion order O(1) อนุญาต 1 null ไม่
TreeSet Sorted order O(log n) ไม่อนุญาต null ไม่
Set.of() ตามที่สร้าง O(1) ไม่อนุญาต null Immutable (thread-safe)