如何在 Java 9 中使用 JShell 實現 HashMap、LinkedHashMap 和 TreeMap?


JShell Java 9 中引入的 命令列 提示工具,它也被稱為 REPL 工具,用於評估簡單語句,執行它,並立即列印輸出。

Map 介面指定了一個契約來實現以 key/value 對形式存在的元素集合。實現 Map 介面的 Java 集合類為 HashMap、LinkedHashMap 和 TreeMap

在下面的程式碼段中,HashMap 元素保證不會以插入順序或鍵的排序順序儲存。

程式碼段-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}


In 下面的程式碼段,LinkedHashMap 的元素已按 插入 順序儲存。

程式碼段-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}


在下面的程式碼段中,TreeMap 的元素已經按 鍵的自然排序順序儲存。

程式碼段-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}

更新於: 01-05-2020

149 次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.