0

I want to compare 2 HashMap Objects, and i want to iterate the values Collection, somthing like this answer.

But can I be sure that the 2 object Iterator will go in the same order?

If not, i thought about the next one, but it not so good looking:

public class MyObject {
    HashMap<Integer, String> myMap = new HashMap<Integer, String>();

    @Override
    public boolean equals(Object obj) {
        if(!(obj instanceof MyObject))
            return false;

        MyObject other = (MyObject)obj;

        if(this.myMap.size() != other.myMap.size())
            return false;

        for (Iterator<Entry<Integer, String>> it = myMap.entrySet().iterator(); it.hasNext(); ) {
            Entry<Integer, String> entry = it.next();
            String otherValue = other.myMap.get(entry.getKey());
            if(otherValue == null || !entry.getValue().equals(otherValue))
                return false;
        }
        return true;
    }
}
  • 3
    *can I be sure that the 2 object Iterator will go in the same order* No, you can't. Maps or not ordered. – Guy Dec 25 '19 at 10:25
  • 3
    Why not use the JDK implementation? `this.myMap.equals(other.myMap)` – Eran Dec 25 '19 at 10:28
  • Indeed, use the JDK implementation. For one, if the value for the same key is `null` in both maps, they should be considered equal, and yours returns false. – RealSkeptic Dec 25 '19 at 10:45
  • *Example where order is different for same values:* Add two entries to a map: `map.put(654321, "A"); map.put(123456, "B");`. Do that to two different maps: `new HashMap<>(2)` and `new HashMap<>(16)`. Print result. Order will be different. Tested on OpenJDK 13. – Andreas Dec 25 '19 at 11:09
  • @Eran, that was my first idea ofcours. But I read online HashMap dosn't override the equals function so it call the Object one. – Netanel Albert Dec 25 '19 at 18:42
  • @NetanelAlbert `HashMap` does override equals (or more specifically: `AbstractMap` does). – Mark Rotteveel Dec 26 '19 at 15:08
  • @MarkRotteveel thank you. that's why i didnt find it on HashMap documentation. – Netanel Albert Dec 28 '19 at 09:46

1 Answers1

2

If you want to compare the insertion order too, use LinkedHashMap.

Instead of

HashMap<Integer, String> myMap = new HashMap<Integer, String>();

Use

Map<Integer, String> myMap = new LinkedHashMap<>();
BHAWANI SINGH
  • 729
  • 4
  • 8
  • 1
    This is not wrong, but `LinkedHashMap` isn't "ordered" (ie basically "indexable") either, it just retains insertion order. – daniu Dec 25 '19 at 11:56