简体   繁体   English

HashMap已按键排序?

[英]HashMap is already sorted by key?

I thought that HashMap is unordered, and when iterating over the keys, you can't know what will be the order? 我认为HashMap是无序的,当迭代键时,你不知道命令是什么? In this example, it looks like the map is already sorted by the keys numbers: 在此示例中,看起来地图已按键编号排序:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
public static void main(String[] args) {

    String[] words = {"Car", "Cat" ,"Hello", "World", "Hi", "Bye", "Dog", "Be"};

    Map<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();

    for (String word: words) {
        Integer len = word.length();
        List<String> l = map.get(len);
        if (l == null) { 
            l = new ArrayList<String>();
            l.add(word); 
            map.put(len, (ArrayList<String>) l);
        }
        else {
            if (! l.contains(word)) 
                l.add(word);
        }           
    }

    System.out.println(map);
}
}

Output: 输出:

{2=[Hi, Be], 3=[Car, Cat, Bye, Dog], 5=[Hello, World]}

True but there is no guarantee of maintaining that order. 是的,但无法保证维持该顺序。

From Hashmap docs 来自Hashmap文档

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 . 特别是,它不保证订单会随着时间的推移保持不变

Your bench mark is not enough to decide over it. 你的替补标记不足以决定它。

Look at TreeMap If you need the sorting order 查看TreeMap如果需要排序顺序

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 地图根据其键的自然顺序进行排序,或者根据使用的构造函数在地图创建时提供的比较器进行排序

For small hashCodes, the HashMap turns into an array (as this is what is used underneath) There is no requirement for it to do so but it happens to be the simplest implementation. 对于小的hashCodes,HashMap变成一个数组(因为这是在下面使用的)没有要求它这样做,但它恰好是最简单的实现。

In short, if you add 0 to 10 to a HashSet or HashMap you will get them in order because the capacity is large enough to just layout those values in order. 简而言之,如果向HashSet或HashMap添加0到10,您将按顺序获取它们,因为容量足够大,可以按顺序布局这些值。

Treemap是一个有序的映射,其中包含按排序顺序排列的键,而HashMap无法保证您排序的map.So,总是在需要排序键时选择Treemap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM