gpt4 book ai didi

Java HashMap 放入数据时没有返回预期结果

转载 作者:行者123 更新时间:2023-12-01 19:31:38 24 4
gpt4 key购买 nike

嗨,我想询问有关 java hashmap 的问题,这是我的代码

     HashMap<String, Object> hash_map = new HashMap<String, Object>(); 

// Mapping string values to int keys
hash_map.put("SP", "A");
hash_map.put("C1", "B");
hash_map.put("C2", "C");

//hash_map.put("C3", "You");

// Displaying the HashMap
System.out.println("Initial Mappings are: " + hash_map);

// Inserting existing key along with new value

hash_map.put("C3", "D");
hash_map.put("C4", "E");
System.out.println("New map is: " + hash_map);

这个结果

Initial Mappings are: {SP=A, C1=B, C2=C}

New map is: {C3=D, C4=E, SP=A, C1=B, C2=C}

我的预期结果

Initial Mappings are: {SP=A, C1=B, C2=C}

New map is: {SP=A, C1=B, C2=C, C3=D, C4=E}

最佳答案

一个HashMaphashCode 排序到存储桶中。要拥有保留插入顺序的 Map,请使用 LinkedHashMap 。就像,

Map<String, Object> hash_map = new LinkedHashMap<>();

关于Java HashMap 放入数据时没有返回预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59639556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com