Java 初学者 : How key gets sorted in hashmaps?

标签 java sorting hashmap key-value

我是 Java 的新手,正在学习 HashMap 的概念。

我对 HashMap 中键的排序方式感到困惑。 我知道它基于字符串长度。 但我很困惑当字符串长度相同时如何对数据进行排序。

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapExample
{

    public static void main(String args[])
    {
        Map<String,String> map = new HashMap<String,String>(20);//SPECIFYING THE TYPE FOR FINDING HASH CODES.


        //Adding values to the HashMap
        map.put("key value a", "test value 1");
        map.put("key value b", "test value 2");
        map.put("key value c", "test value 3");

        System.out.println("Retrieving values from HashMap");
        retrieveValuesFromListMethod(map);
        System.out.println("**********************");


    }

    /*This method retrieves values from Map
     */
    public static void retrieveValuesFromListMethod(Map map)
    {
        Set keys = map.keySet();
        Iterator itr = keys.iterator();

        String key;
        String value;

        while(itr.hasNext())
        {
            key = (String)itr.next();
            value = (String)map.get(key);
            System.out.println(key + " - "+ value); 
        }
    }
}

这是我的代码。

输出是

Retrieving values from HashMap
key value c- test value 3
key value b- test value 2
key value a- test value 1
**********************

但是如果我给 aa,ab,ac 而不是 a,b,c 输出是不同的

Retrieving values from HashMap
key value ab - test value 2
key value aa - test value 1
key value ac - test value 3
**********************

对于 1,2,3

Retrieving values from HashMap
key value 1 - test value 1
key value 2 - test value 2
key value 3 - test value 3
**********************

hashmap 是如何排序的?请帮忙!!

提前致谢。

最佳答案

java.util.HashMap is unordered; you can't and shouldn't assume anything beyond that.

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

java.util.LinkedHashMap uses insertion-order.

This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

java.util.TreeMap, a SortedMap, uses either natural or custom ordering of the keys.

The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

关于Java 初学者 : How key gets sorted in hashmaps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18504121/

相关文章:

java - Hibernate findById 的问题

javascript - 如果显式定义排序顺序,排序会非常慢

sorting - mapreduce 分区内的数据是否已排序,如果是,它是如何发生的?

arrays - 重新排列整数数组

java - 组合 2 个 HashMap 并返回 String

java - 如何根据 HashMap 的键和值检查两个输入?

java - 使用可选值填充映射中的值

java - Log4j 在写入文件时跳过内容

java - 反转 HashMap

java - 带有 Android 的 Azure 移动服务