Posts

Showing posts from September, 2018

Importance of equals and hashcode method override

Importance of equals and hashcode method override: Both equals and hashcode method present in java.lang.Object, hence these methods available for all java classes. When comparing the objects, these methods are used. Default implentation: equals -> checks two objects are pointing same memory location (== check) hashcode ->  returns an integer representation of the object memory address. By default, this method returns a random integer that is unique for each instance. This integer might change between several executions of the application and won't stay the same. Note :  "If two objects are equal according to the  equals(Object)  method, then calling the  hashcode()  method on each of the two objects must produce the same integer result." Example: We will define Student class with and without overriding equals & hashcode. Student.java public class Student {        private int id;        ...