Skip to main content

Posts

Showing posts with the label Equals

How does equals() method work in Java

Points To Remember equals() , method is a method of the Object class, hence is available in all classes. Syntax of equals in Object class is public boolean equals(Object obj) . It return true if two objects are same, in object class it just checks if the two references points to the same class.  We can override the equals method to provide custom logic to say the two objects are same. See  How to override equals method ,  Concept: Making two objects same. Suppose we have a Book class and each object represents a book. We create three objects book1, book2 and book3 (new keyword always creates a new object) and the objects book1, book2 refer to same book same with name 'Think Think' and id '1', book 3 refers to book 'Bad Kitty'. So in real case scenario the book1 and book2 objects should be same or equal. id=1, name = Think Think  id=2, name= Bad Kitty So lets check how many objects are created and if they are equal when their member variables are same. (According...

Contract between equals() and hashCode()

Points To Remember Both the method equals() and hashCode()  are the methods of Object class, hence available in all the classes. Syntax for equals() method in Object class is public boolean equals(Object obj) Syntax for hashCode() method in Object class is public int hashCode() The equals()  method of Object class checks if the two references compared point to same object , returns true if they are same and false if two objects are different. We can override this functionality by our own custom way of comparing objects. If the equals() method returns true, then the hashcode() of the two object must be same. If hashCode() of two objects are same, it does not mean that the objects should be same. Concept : equals() & hashCode() method in Object class  First of all lets see what does an equals() method do in java. The equals method in the object class is used to see that if the two object references are pointing to the same object. See how equals() method works. ...