HashMap已按键排序? [英] HashMap is already sorted by key?

查看:105
本文介绍了HashMap已按键排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为HashMap是无序的,当迭代键时,你不知道命令是什么?在此示例中,看起来地图已按键编号排序:

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);
}
}

输出:

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


推荐答案

是的,但无法保证维持该订单。

True but there is no guarantee of maintaining that order.


来自 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.

看看 TreeMap 如果您需要排序顺序

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

这篇关于HashMap已按键排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆