当用Integer键迭代HashMap时,它是否总是按照升序返回键? [英] When iterating through a HashMap with Integer keys, will it always return keys in ascending order?

查看:183
本文介绍了当用Integer键迭代HashMap时,它是否总是按照升序返回键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HashMap定义为:

public Map< Integer,String> staticBlockPositions = new HashMap< Integer,String>();



我通过获取每个键来迭代地图,对于(整数键:blockPositions.keySet()){
System.out.println(key); $ p

  
}

我的问题是,我可以依赖键始终按升序排列。所以如果我的HashMap看起来像这样:

  {
4:abc123,
1: def456,
11:qwe789,
10:iop019
}

(我知道这是JSON格式,这只是让您了解数据集)。



我的循环始终输出

  1 
4
10
11

无论我的数据顺序如何?



重要的是要注意,密钥添加的顺序完全是随机的,我无法控制什么时候添加密钥。



这是为了俄罗斯方块风格的游戏,所以从小到大依次是必须

解决方案

引用 Javadoc


这个类不能保证t的顺序他映射;特别是,它不能保证订单会随着时间的推移保持不变。

整数键没有特殊情况。您无法依赖订单。



如果您希望按键升序排列,请使用 SortedMap ,例如 TreeMap


I have a HashMap defined as such:

public Map<Integer, String> staticBlockPositions = new HashMap<Integer, String>();

I am iterating over the map by getting each key, like this:

for (Integer key : blockPositions.keySet()) {
    System.out.println(key);
}

My question is, can I rely on the value of key to always be in ascending order. So if my HashMap looks something like this:

{
    4: "abc123",
    1: "def456",
    11: "qwe789",
    10: "iop019"
}

(I know this is JSON format, this is just so you get an idea of the data set).

Will my loop always output

1
4
10
11

regardless of the order of my data?

Important to note, the order in which the keys are add is completely random, and I cannot control what key is added when.

This is for a Tetris style game, so getting the keys in ascending order is a must.

解决方案

Quoting the Javadoc:

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.

There is no special case for integer keys. You simply can't rely upon the order.

If you want the keys to be in ascending order, use an implementation of SortedMap, like TreeMap.

这篇关于当用Integer键迭代HashMap时,它是否总是按照升序返回键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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