【问题标题】:How to use original hashCode() method after overriding it覆盖后如何使用原始 hashCode() 方法
【发布时间】:2013-08-02 15:26:47
【问题描述】:

//Student.java

class Student{
private int roll;
private String name;

    public Student(int roll,String name){
    this.roll=roll;
    this.name=name;
    }

    public int hashCode(){
    return roll+name.length();
    }

    public  boolean equals(Object obj){
    Student s=(Student)obj;
    return (this.roll==s.roll && this.name.equals(s.name));
    }

}

//IssueID.java

class IssueID{

    public static void issueID(Student s1,Student s2){

    if(s1.equals(s2))
    System.out.println("New ID issued");

    else
    System.out.println("New ID NOT issued");

    }

}

//Institute.java

import java.lang.Object;
class Institute{
    public static void main(String[] args){
    Student s1=new Student(38,"shiva");
    Student s2=new Student(45,"aditya");

    IssueID.issueID(s1,s2);


    System.out.println(s1.hashCode());
    System.out.println(s2.hashCode());
    }

}

在上面的代码中,我已经覆盖了hashCode() 方法。这听起来很傻,但是我可以同时使用相同的学生对象(s1 和 s2)访问java.lang.Object.hashCode() 方法吗?

【问题讨论】:

  • super.hashCode(),但恕我直言,这没有用。

标签: java


【解决方案1】:

是的,System.identityHashCode:

为给定对象返回与默认方法 hashCode() 返回的相同的哈希码,无论给定对象的类是否覆盖 hashCode()。

【讨论】:

    【解决方案2】:

    这样写:

    class Student {
        public int originalHashCode() {
            return super.hashCode();
        }
    }
    

    然后在你想使用原始的时候调用s.originalHashCode()~

    【讨论】:

      【解决方案3】:

      您可以使用System.identityHashCodesuper.hashCode() 另外,您应该编写一个更好的哈希码,因为任何学生的姓名长度和滚动的总和相等都将具有相同的哈希码。像 (9, "Bob") 和 (7, "Steve")。这将为未来的错误带来许多潜在问题。省得自己头疼,写这样的东西:

       public int hashCode() {
            int hash = 31 * roll;
            hash = 31 * hash + name.hashCode();
            return hash;
       }
      

      另外,请注意,您的 equals 方法不满足 JLS 中的 equals 方法。

      this.equals(null) 应该返回 false,你的会抛出 ClassCastException。

      这也可能导致将来出现错误。

      【讨论】:

      • 是的!该哈希码方法仅用于测试。无论如何感谢您的建议!
      • HashCodeBuilder 是你的朋友!
      猜你喜欢
      • 2021-04-30
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 2020-06-06
      • 2014-10-06
      • 2020-06-09
      • 1970-01-01
      相关资源
      最近更新 更多