How to use the original hashCode () method after overriding it

//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()); } } 

As in the code above, I overridden the hashCode() method. This may sound silly, but can I access the java.lang.Object.hashCode() method using the same Student objects (s1 and s2) at the same time?

+6
source share
3 answers

Yes, System.identityHashCode :

Returns the same hash code for this object, which will be returned by the hashCode () method by default, regardless of whether or not this class of the hashCode () object overrides.

+17
source

You can use System.identityHashCode or super.hashCode() . In addition, you should write the best hash code, since all students with the sum of the name and roll lengths equal will have the same hash code. Like (9, "Bob") and (7, "Steve"). This will open up many potential problems for future mistakes. Save yourself from headaches and write something like this:

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

Also, keep in mind that your equals method does not satisfy the equals method in JLS.

this.equals(null) should return false, yours will throw a ClassCastException.

It may also lead to errors in the future.

0
source

write something like this:

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

then call s.originalHashCode () if you want to use the original ~

0
source

Source: https://habr.com/ru/post/950913/


All Articles