1

I am extending a HashMap to implement a class that documents the solution steps for an equation:

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

So far, I have not had a problem with the order of these entries when testing - I will add test entries, and the toString() will print them out in the correct ordering and numbering, i.e.

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

Will produce the output in the intended order:

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

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

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85

1 Answers1

2

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

Absolutely not, on the contrary. The ordering of a HashMap is arbitrary, and inserting new elements may change the ordering. Running the same code on a different JVM implementation (or a different version) may also change the ordering. According to 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.

So you cannot rely on the order here. If you need an ordered associative map structure, you need to use e.g. a TreeMap.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214