简体   繁体   中英

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? 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

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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