Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách triển khai interface Set trong JShell Java 9?

JShell là công cụ command-line trong Java 9 dùng để thực thi câu lệnh đơn giản như biểu thức, class, interface, method...

Set là interface trong Java quy định hợp đồng cho tập hợp có phần tử duy nhất. Nếu object1.equals(object2) trả về true thì chỉ một trong hai object có chỗ trong triển khai Set.

Đoạn mã dưới dùng phương thức Set.of(). Collection trả về là immutable, không hỗ trợ add(). Thử thêm phần tử ném UnsupportedOperationException. Muốn tạo HashSet hỗ trợ add() để kiểm tra tính duy nhất. Trả về false cho thấy thêm bản sao "Adithya" thất bại.

Đoạn mã 1

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]

Đoạn mã dưới triển khai HashSet: phần tử không theo thứ tự thêm cũng không theo thứ tự sắp xếp.

Đoạn mã 2

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]

Đoạn mã dưới triển khai LinkedHashSet: phần tử lưu theo thứ tự thêm vào.

Đoạn mã 3

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]

Đoạn mã dưới triển khai TreeSet: phần tử lưu theo thứ tự sắp xếp.

Đoạn mã 4

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]