Override Equals for Hashmap<String,String>

社会主义新天地 提交于 2019-12-25 08:27:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!