Pradheep
Pradheep

Reputation: 139

Override Equals for Hashmap<String, String>

I have Hashmap<String, String>, how to override equals method for the hashmap?

Thanks.

Upvotes: 0

Views: 1618

Answers (4)

Daniel Gabriel
Daniel Gabriel

Reputation: 3985

Or better yet, make a separate method somewhere to compare the specific hashmaps you want. For example:

public class HashMapComparator {
    boolean static areMapsEqual(HashMap<String, String> aMap, HashMap<String, String> bMap) {
        ....
    }
}

Then to use it:

boolean mapsAreEqual = HashMapComparator.areMapsEqual(firstMap, secondMap);

Although you should know that this is an incorrect solution in case you want to use your equals method when searching or sorting lists of these HashMaps. I'm assuming that is not the case.

Upvotes: 0

KiKMak
KiKMak

Reputation: 830

You will need to make a class of your own which extends Hashmap

public class NewHashMap<K,V> extends HashMap<K, V>

and override the equals method in that

@Override
public boolean equals(Object o) {
    // Your code
}

Good Luck

Upvotes: 0

Naveen
Naveen

Reputation: 535

In HashMap already equals() method is overrriden.If you want to override object class equals() method eclipse shortcut key--->alt+shift+s+v

Select the equals method click on ok.

Upvotes: 0

Martin
Martin

Reputation: 1273

if you want you can do:

HashMap<String, String> map = new HashMap<String, String>(){
    @Override
    public boolean equals(Object o) {
        // TODO comparison here
        return super.equals(o);
    }
};
map.equals(new HashMap<String, String>());

Upvotes: 1

Related Questions