what is the difference between == operator and equals()? (with hashcode() ???)

the == operator determines if 2 references point to the same object.

So

 Object o1 = new Object();
 Object o2 = o1;

 o1 == o2; //true

 o2 = new Object();

 o1 == o2 // false

the Object.equals() method is “how do I determine if 2 references to objects, that are not the same object, are equal?”

If two references point to the same object, both

o1 == o2 
o1.equals(o2) 

should be true.

But if o1 and o2 are not the same object, they still might be equal logically. For any given class, equals depends on the semantics behind the object. For example, consider a class where field1 and field2 are set by the user, but field3 is computed and has a random element to its computation. It might make sense to define equals in this case to only depend on field1 and field2, and not field3. Thats why equals is necessary.

Leave a Comment