0

I have the below Java code, I have overridden equal,but not hashCode.

My requirement is to check whether the two objects of class HashCodeSampleMain are having same values are not.

I am able to do it without overriding hashCode.

public class HashCodeSampleMain {

    public static void main(String[] args) {

        HashCodeSample obj1 = new HashCodeSample(100, "surender");
        HashCodeSample obj2 = new HashCodeSample(100, "surender");

        if (obj1.equals(obj2))
        {
            System.out.println("both objects are same");
        }

    }

 }

 public class HashCodeSample {

     int id =0;
     String name=null;

     public HashCodeSample(int temp_id, String temp_name)
     {
         id =temp_id;
         name =temp_name;
     }

     @Override
     public boolean equals(Object obj) {

         HashCodeSample m =(HashCodeSample)obj;

         if(this.id ==m.id && this.name ==m.name)
         {
             return true;
         }

         else 
         {
             return false;
         }

    }

}

Output

 both objects are same

I want to understand what is importance of hashCode in connection with equal method.

Mohammadreza Khatami
  • 1,444
  • 2
  • 13
  • 27
Surender Raja
  • 3,553
  • 8
  • 44
  • 80
  • You only need to implement methods you use (or might use in the future) – Peter Lawrey Jul 30 '16 at 10:39
  • `hashCode()` is needed for keys and elements of hash collections. If you *know* you are never going to use them that way, you don't need to implement `hashCode()` – Peter Lawrey Jul 30 '16 at 10:40
  • @ Peter , So in above example of my java code there is no need to implement hashCode .. Is My understanding is correct? – Surender Raja Jul 30 '16 at 10:43
  • Need to, no, should, yes. @SurenderRaja since you'll never be able to guarantee who 'll use your code (in the end) or what you'll be using it for in the future, it's usually a good choice to implement it whether you need it now or not – Stultuske Jul 30 '16 at 10:44
  • @SurenderRaja you may also want to check your equals method. comparing String objects using == might lead to unexpected (wrong) results – Stultuske Jul 30 '16 at 10:46
  • Sure, I will apply equals for String Comparison, Thanks for your help – Surender Raja Jul 30 '16 at 10:47
  • Also you should not throw a ClassCastException when comparing with other Objects in equals. Just return false instead. – garnulf Jul 30 '16 at 10:59

0 Answers0