简体   繁体   English

如何重写String类的hashcode方法?

[英]How to override String class's hashcode method?

I want to override String classes Hashcode / Equals methods as I know the String class is final and the method inside that can not be overridden. 我想重写String类的Hashcode / Equals方法,因为我知道String类是最终的,并且其中的方法不能被覆盖。 I have a scenario where I want to apply the same. 我有一种情况,我想应用同样的方法。 for instance code is given below, 例如下面的代码,

public static void main(String[] args) {

        Map<String,Integer> map = new HashMap();
        map.put("Mukul", 1);
        map.put("Aditya", 1);

        System.out.println(map);


    } 

As I am passing string as a key and map is gonna call String classes hashcode method implicitly. 当我将字符串作为键传递时,映射将隐式调用String类的hashcode方法。 Now I want to declare that the given keys are same in my way. 现在,我想声明给定的键与我的方式相同。 Please suggest if there is any way to do so? 请建议是否有办法?

You can create your own custom String class that contains a String member and implements equals and hashCode as you see fit, and use a Map<MyString,Integer> : 您可以创建自己的包含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);
    } 
}

As a comment already state to make a wrapper of the String class with its own hashcode and equals , here is another solution: you can use a TreeMap , and provide it with your own Comparator : 正如已经声明要用其自己的hashcodeequalsString类进行包装的注释一样,这是另一种解决方案:您可以使用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
        } 
    });

(inspired by Java TreeMap Comparator ) (受Java TreeMap Comparator的启发)

没有办法用字符串来做到这一点,而是创建自己的对象并在从地图中获取数据后对其进行处理。即使您创建自己的字符串类,也不会与已经存在的字符串类兼容,就像没有MyString obj = “名称”;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM