我可以保证 HashMap 的 entrySet() 的顺序吗?

Am I guaranteed this ordering for a HashMap's entrySet()?

我正在扩展 HashMap 来实现 class 记录方程的求解步骤:

public class SolutionSteps extends HashMap<Integer, String>
{
    private int currentStep;

    public SolutionSteps ()
    {
        super();
        currentStep = 1;
    }

    public final void addStep (@NotNull final String value)
    {
        put(currentStep, value);
        currentStep++;
    }

    @Override
    @NotNull
    public final String toString ()
    {
        StringBuilder sb = new StringBuilder(50 * size());

        for(Entry<Integer, String> entry : entrySet())
        {
            sb.append(entry.getKey()).append(": " ).append(entry.getValue()).append('\n');
        }

        return sb.toString().trim();
    }
}

到目前为止,我在测试时没有遇到这些条目的顺序问题 - 我将添加测试条目,toString() 将以正确的顺序和编号打印出来,即

SolutionSteps steps = new SolutionSteps();
steps.addStep("First");
steps.addStep("Second");
steps.addStep("Third");
steps.addStep("Fourth");
steps.addStep("Fifth");

将按预期顺序生成输出:

1: First
2: Second
3: Third
4: Fourth
5: Fifth

我的问题是,这个条目集的排序是否保证

My question is, is this ordering of the entry set guaranteed?

绝对不是,恰恰相反。 HashMap的排序是任意,插入新元素可能改变排序。 运行 不同 JVM 实现(或不同版本)上的相同代码可能 更改顺序。根据the documentation:

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.

所以你不能依赖这里的顺序。如果您需要有序的关联映射结构,则需要使用例如TreeMap.