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

วิธีใช้ HashMap, LinkedHashMap, และ TreeMap ใน JShell Java 9

JShell เป็นเครื่องมือ command-line prompt ที่มาพร้อม Java 9 เรียกอีกอย่างว่า REPL tool ใช้ประเมินคำสั่งง่ายๆ และแสดงผลทันที

Interface Map กำหนด contract สำหรับ collection ที่เก็บข้อมูลแบบ key/value pairs คลาสที่ implements Map interface ได้แก่ HashMap, LinkedHashMap, และ TreeMap

HashMap - ไม่รับประกันลำดับ

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}

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

LinkedHashMap - รักษา insertion order

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}

ลำดับ: ตาม insertion order (Raja → Adithya → Surya → Vamsi)

TreeMap - เรียงลำดับตาม key แบบ natural order

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}

ลำดับ: เรียงตาม alphabetical order ของ key (Arjun → Manoj → Pavan → Raj)

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

Implementation ลำดับข้อมูล Performance (get/put) Null Key/Value
HashMap ไม่มีลำดับ O(1) อนุญาต null key 1 ตัว, null value หลายตัว
LinkedHashMap Insertion order O(1) อนุญาต null key 1 ตัว, null value หลายตัว
TreeMap Sorted (natural/comparator) O(log n) ไม่อนุญาต null key, อนุญาต null value