Goldman Sachs Interview Question
Software Engineer / DevelopersCountry: United States
Best practise are
1. reflexive for non null reference value x, x.equals(x) should be true
2. Symmetic for non null refrence values x and y. x.equals(y) should return true iff y.equals(x) returns true
3. transitive for non null reference values x,y and Z if x.equals(y) and y.equals(z) then x.equals(z) should return true
4. Consistent i.e. x.equals(y) should always return true irrespective of the number of call made
5. For any non null reference x x.equals(null) should return false.
How about calling hashcode on two object and if they return same value then its equals else they are not.
1. All objects are subclasses of java.lang.Object.
- enzeart August 15, 20142. Reflexive, symmetric, transitive, consistent, and type aware, as mentioned above by Prince
are important attributes of an equals function. The equals method is closely related to the hashCode method in that they both speak about the identity of the object in question. If you override the equals method it is a good practice to override the hashCode method as well to ensure that two equal object return the same hashCode output.
3. The equals method should be implemented with the nature of the object in mind. An immutable object with hundreds of fields can have an optimized equals method which involves the object creating a hash-based id of itself upon initialization and comparing that value between two target objects when the equals method is invoked. For increasingly write-heavy objects a similar approach can be taken where hashes are generated for the more stable set of fields to optimize the average cost of comparison.