有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在使用整数键遍历HashMap时,是否总是以升序返回键?

我有一个定义如下的HashMap:

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

我通过获取每个关键点在地图上迭代,如下所示:

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

我的问题是,我是否可以依赖key的值始终以升序排列。因此,如果我的HashMap看起来像这样:

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

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

我的循环是否总是输出

1
4
10
11

不管我的数据顺序如何

重要的是要注意,添加键的顺序是完全随机的,我无法控制何时添加哪个键

这是一款俄罗斯方块风格的游戏,因此按升序获得钥匙是一项必须的任务


共 (3) 个答案

  1. # 1 楼答案

    1. 要保持排序顺序,请使用树形图

    2. 要保持插入顺序,请使用LinkedHashMap

  2. # 2 楼答案

    引用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.

    整数键没有特殊情况。你根本不能依赖订单

    如果希望键按升序排列,请使用SortedMap的实现,如^{}

  3. # 3 楼答案

    除了@AndyTurner所说的HashMap不能保证秩序之外,似乎TreeMap还提供了您想要的功能