Basically, ==
compares if two objects have the same reference on the heap, so unless two references are linked to the same object, this comparison will be false.
equals()
is a method inherited from Object
class. This method by default compares if two objects have the same referece. It means:
object1.equals(object2)
<=> object1 == object2
However, if you want to establish equality between two objects of the same class you should override this method. It is also very important to override the method hashCode()
if you have overriden equals()
.
Implement hashCode()
when establishing equality is part of the Java Object Contract. If you are working with collections, and you haven't implemented hashCode()
, Strange Bad Things could happen:
HashMap<Cat, String> cats = new HashMap<>();
Cat cat = new Cat("molly");
cats.put(cat, "This is a cool cat");
System.out.println(cats.get(new Cat("molly"));
null
will be printed after executing the previous code if you haven't implemented hashCode()
.