I was learning hashcode in more depth and figured that:
1. If you override equals(), you must override hashcode() too.
2. To find if
==
operator --> checks weather 2 references point to the same object or not. If same it return true otherwise false.
equals( )
--> checks both reference and state object. Hear state means object data. In this any one is true it returns true. Otherwise false. But we have to override equals( )
in our user defined object and write the appropriate code.
Hashcode( )
-->hashCode of an Object just represents a random number which can be used by JVM while saving/adding Objects into Hashsets, Hashtables or Hashmap.
Example of hashcode()
class TestHasChode
{
int i;
TestHasChode(int i)
{
this.i = i;
}
public static void main(String arg[])
{
//before overriding hashcode()
TestHasChode t1 = new TestHasChode(100);
TestHasChode t2 = new TestHasChode(110);
System.out.println(t1); //TestHasChode@45e41830
System.out.println(t2); //TestHasChode@1f01b29
TestHasChode t3 = new TestHasChode(100);
TestHasChode t4 = new TestHasChode(100);
System.out.println(t3); //TestHasChode@3a8721bd
System.out.println(t4); //TestHasChode@7db81d4f
/*hashCode() of Object class implemented to return hashCode based on address of an object, but based
on our requirement we can override hashCode() to generate our own numbers as hashCodes*/
//after overriding hashcode()
System.out.println(t3); //TestHasChode@64
System.out.println(t4); //TestHasChode@64
}
public int hashCode(){
return i;
}
}
-->Example of equals()method
class Student
{
String name;
int rollno;
Student(String name,int rollno)
{
this.name = name;
this.rollno = rollno;
}
public static void main(String arg[])
{
//before overrideng equals method
Student s1 = new Student ("raju", 101);
Student s2 = new Student ("giri", 102);
Student s3 = new Student ("giri", 102);
System.out.println(s1.equals(s2));//false
System.out.println(s2.equals(s3));//false
//after overriding equals method
System.out.println(s1.equals(s2));//false
System.out.println(s2.equals(s3));//true-->hear overriding equals() checks state.so it is true.
//in string variables comparisition
String s4="hello";
String s5=new String("hello");
String s6=new String("hello");
System.out.println(s4.equals(s5));//true--> because String class containg overridden equals method
System.out.println(s5.equals(s6));//true-->even though differnet object reference but String class containg overridden equals method
}
public boolean equals(Object obj){
String name1 = this.name;
int rollno1 = this.rollno;
Student s2 = (Student)obj;
String name2 = s2.name;
int rollno2 = s2.rollno;
if(name1.equals(name2) && rollno1 == rollno2){
return true;}
else{
return false;}
}
}