当用Integer键迭代HashMap时

当用Integer键迭代HashMap时

本文介绍了当用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

无论我的数据顺序如何?



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



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

解决方案

引用:

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



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


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:

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时,它是否总是按照升序返回键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:18