如何在 Java 9 中的 JShell 中实现 HashMap、LinkedHashMap 和 TreeMap?

javaobject oriented programmingprogramming更新于 2025/11/13 14:36:17

JShell 是 Java 9 中引入的 命令行 提示工具,也称为 REPL 工具,用于评估简单语句、执行它并立即打印输出。

Map 接口指定一个契约,以 键/值对的形式实现元素集合。实现 Map  接口的 Java 集合类有 HashMap 。

在下面的代码片段中,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}

在下面的代码片段中,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}

相关文章


有用资源