嗨,我想问一下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);


这个结果


  
    初始映射为:{SP = A,C1 = B,C2 = C}
    
    新地图为:{C3 = D,C4 = E,SP = A,C1 = B,C2 = C}
  


我的预期结果


  
    初始映射为:{SP = A,C1 = B,C2 = C}
    
    新地图为:{SP = A,C1 = B,C2 = C,C3 = D,C4 = E}

最佳答案

HashMaphashCode排序到存储桶中。要使Map保留插入顺序,请使用LinkedHashMap。喜欢,

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

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

10-14 11:59