//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?
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With