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

Cách triển khai HashMap, LinkedHashMap và TreeMap trong JShell Java 9?

JShell là công cụ command-line giới thiệu trong Java 9, còn gọi là công cụ REPL để đánh giá câu lệnh đơn giản, thực thi và in kết quả ngay lập tức.

Interface Map quy định hợp đồng triển khai tập hợp phần tử dạng cặp key/value. Các lớp collection triển khai Map bao gồm HashMap, LinkedHashMap, và TreeMap.

Đoạn mã dưới đây minh hoạ: phần tử của HashMap không đảm bảo thứ tự thêm vào hay thứ tự sắp xếp của key.

Đoạn mã 1

jshell> HashMap<String, Integer> hashMap = new HashMap<>(); 
hashMap ==> {} 
jshell> hashMap.put("Adithya", 101); 
$2 ==> null 
jshell> hashMap.put("Jai", 102); 
$3 ==> null 
jshell> hashMap.put("Chaitanya", 103); 
$4 ==> null 
jshell> hashMap.put("Ravi", 104); 
$5 ==> null 
jshell> hashMap 
hashMap ==> {Chaitanya=103, Jai=102, Ravi=104, Adithya=101}

Đoạn mã dưới đây: phần tử của LinkedHashMap được lưu theo thứ tự thêm vào.

Đoạn mã 2

jshell> LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>(); 
linkedHashMap ==> {} 
jshell> linkedHashMap.put("Raja", 101); 
$8 ==> null 
jshell> linkedHashMap.put("Adithya", 102); 
$9 ==> null 
jshell> linkedHashMap.put("Surya", 103); 
$10 ==> null 
jshell> linkedHashMap.put("Vamsi", 104); 
$11 ==> null 
jshell> linkedHashMap 
linkedHashMap ==> {Raja=101, Adithya=102, Surya=103, Vamsi=104}

Đoạn mã dưới đây: phần tử của TreeMap được lưu theo thứ tự tự nhiên của key.

Đoạn mã 3

jshell> TreeMap<String, Integer> treeMap = new TreeMap<>(); 
treeMap ==> {} 
jshell> treeMap.put("Raj", 101); 
$14 ==> null 
jshell> treeMap.put("Pavan", 102); 
$15 ==> null 
jshell> treeMap.put("Arjun", 103); 
$16 ==> null 
jshell> treeMap.put("Manoj", 104); 
$17 ==> null 
jshell> treeMap 
treeMap ==> {Arjun=103, Manoj=104, Pavan=102, Raj=101}