-4

I am writing simple code by overriding hashcode and equels method can any one plz expline me how that will work exactly if i overried or not overried in my class.

class HexToDec {
      public static void main(String[] args) {
            Test t = new Test();
    //        Test t1 = new Test("Aamir", true, "good lead, choclate hero");
            Test t3 = new Test();
            Test t4 = new Test();
            t4.setName("ranjith");
            System.out.println("a1.hashCode() = " + t);
            System.out.println("a2.hashCode() = " + t4);
            System.out.println("a1.hashCode() = " + t3.hashCode());
            System.out.println("a2.hashCode() = " + t4.hashCode());
    //        System.out.println("is a1 == a2 " + (t == t1));
            System.out.println("is a1.equals(a2) " + (t3.equals(t4)));
        }
    }

1 Answers1

-1

you have to override hashCode() method whenever you override equals(). because, hashcode is used to uniquely identify each object. If 2 objects are equal, then they should be having the same hashcode. Once you change the equals() method, you override hashCode() to make it understand on what grounds two objects can be considered equal.

http://javapapers.com/core-java/hashcode-and-equals-methods-override/

TheLostMind
  • 34,842
  • 11
  • 64
  • 97