问题
I have Hashmap,how to override equals method for the hashmap?
Thanks.
回答1:
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>());
回答2:
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.
回答3:
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
回答4:
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.
来源:https://stackoverflow.com/questions/22904511/override-equals-for-hashmapstring-string