Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use original hashCode() method after overriding it

Tags:

java

//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 above code, I've overridden the hashCode() method. This may sound silly, but can I access java.lang.Object.hashCode() method using the same Student objects(s1 and s2) at the same time?

like image 452
Shiva Mothkuri Avatar asked Aug 02 '13 15:08

Shiva Mothkuri


1 Answers

Yes, with System.identityHashCode:

Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().

like image 171
Louis Wasserman Avatar answered Nov 08 '22 06:11

Louis Wasserman