0

Saying that there is a list and I add some stuffs in it:

list.add(new Stuff("Test1"))
list.add(new Stuff("Test2"))
list.add(new Stuff("Test3"))
list.add(new Stuff("Test4"))
list.add(new Stuff("Test5"))

and if I put it in the hashmap like this:

private static HashMap<Integer, Report> hashMap = new HashMap<>();

public static void getStuffs(Stuff stuff) {

        int hashCode = stuff.hashCode();

        if (!hashMap.containsKey(hashCode)) {
            hashMap.put(hashCode, stuff);
        }
    }

And when I print the values that are stored in the hashMap, the expected output is:

Test1
Test2
Test3
Test4
Test5

But it is actually stored in the hashMap in a strange order.

Could someone please tell me how to solve this problem?

I tried

1 Answers1

2

Use a LinkedHashMap instead of a HashMap. As you can learn from the documentation also, the main difference between HashMap and LinkedHashMap is that a LinkedHashMap maintains the insertion order of keys (i.e. the order in which keys are inserted into the LinkedHashMap) while a HashMap does not maintain any order of keys.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110