如何覆盖字符串类的哈希码方法?



我想覆盖字符串类Hashcode/Equals方法,因为我知道字符串类是最终的,里面的方法不能被覆盖。我有一个场景,我想用同样的方法。示例代码如下:

public static void main(String[] args) {
        Map<String,Integer> map = new HashMap();
        map.put("Mukul", 1);
        map.put("Aditya", 1);
        System.out.println(map);

    } 

当我传递string作为键时map会隐式调用string类的hashcode方法。现在我想声明给定的键和我的方式是一样的。请问有什么办法可以这样做?

您可以创建自己的自定义String类,其中包含String成员并实现equalshashCode,并使用Map<MyString,Integer>:

public class MyString {
    private String value;
    public MyString (String value) {this.value = value;}
    public int hashCode () {
        ...
    }
    public boolean equals (Object other) {
        ...
    }
    public static void main(String[] args) {
        Map<MyString,Integer> map = new HashMap<>();
        map.put(new MyString("Mukul"), 1);
        map.put(new MyString("Aditya"), 1);
        System.out.println(map);
    } 
}

前面已经说过要用hashcodeequals来包装String类,这里有另一个解决方案:您可以使用TreeMap,并为它提供自己的Comparator:

TreeMap<String, Integer> myMap = 
    new TreeMap<String, Integer>(new Comparator<Entry<String, Integer>>()
    {
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2)
        {
            return o1.getValue().compareTo(o2.getValue()); // your method here
        } 
    });

(灵感来自Java TreeMap Comparator)

对于string没有办法做到这一点,而是创建自己的对象并在从map获得数据后处理它。即使创建自己的字符串类,它也不会与已经存在的字符串类兼容MyString ="name";

最新更新