Explain the relationship between equals and hashcode in java

Equals and Hash Code in Java

explain the relationship between equals and hashcode in java

senshido.info has two very important methods defined: public boolean equals( Object obj) and public int hashCode(). equals() In java equals() method is used to compare equality of two Objects. . Related link: Overriding equal in Java. Learn contract between hashCode and equals methods. and equals() methods have been defined in Object class which is parent class for java objects. Both equals() and hashCode() are defined in senshido.info By the way, this is one of the confusing bit of equals and hashcode contract.

The modification may take place in any one of them or in both of them. You have to ensure that your implementation of the equals method returns false if a null is passed to it as an argument.

10 Equals and HashCode Interview Questions in Java

It simply means that if two objects are equal, then they must have the same hash code, however the opposite is NOT true. This is discussed in details later in this article. The details about these two methods are interrelated and how they should be overridden correctly is discussed later in this article.

This method returns the hash code value as an integer and is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet etc.

explain the relationship between equals and hashcode in java

This method must be overridden in every class that overrides the equals method. This method is supported for the benefit of hashtables such as those provided by java. The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.

This integer need not remain consistent from one execution of an application to another execution of the same application. 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.

It is not required that if two objects are unequal according to the equals java. Object method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

explain the relationship between equals and hashcode in java

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.

As compared to the general contract specified by the equals method, the contract specified by the hashCode method is relatively simple and easy to understand. It simply states two important requirements that must be met while implementing the hashCode method. The third point of the contract, in fact is the elaboration of the second point.

Let's understand what this contract really means. Consistency during same execution - Firstly, it states that the hash code returned by the hashCode method must be consistently the same for multiple invocations during the same execution of the application as long as the object is not modified to affect the equals method. It simply emphasizes the same relationship - equal objects must produce the same hash code. However, the third point elaborates that unequal objects need not produce distinct hash codes.

After reviewing the general contracts of these two methods, it is clear that the relationship between these two methods can be summed up in the following statement - Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

The rest of the requirements specified in the contracts of these two methods are specific to those methods and are not directly related to the relationship between these two methods. Those specific requirements are discussed earlier.

Working With hashcode() and equals()

This relationship also enforces that whenever you override the equals method, you must override the hashCode method as well. Failing to comply with this requirement usually results in undetermined, undesired behavior of the class when confronted with Java collection classes or any other Java classes. Correct Implementation Example The following code exemplifies how all the requirements of equals and hashCode methods should be fulfilled so that the class behaves correctly and consistently with other Java classes.

This class implements the equals method in such a way that it only provides equality comparison for the objects of the same class, similar to built-in Java classes like String and other wrapper classes.

Java hashCode() and equals() – Contract, rules and best practices

The class Test has two member variables - num and data. These two variables define state of the object and they also participate in the equals comparison for the objects of this class. Hence, they should also be involved in calculating the hash codes of this class objects. Consider the equals method first. We can see that at line 8, the passed object reference is compared with this object itself, this approach usually saves time if both the object references are referring to the same object on the heap and if the equals comparison is expensive.

Next, the if condition at line 10 first checks if the argument is null, if not, then due to the short-circuit nature of the OR operator it checks if the argument is of type Test by comparing the classes of the argument and this object.

explain the relationship between equals and hashcode in java

This is done by invoking the getClass method on both the references. If either of these conditions fails, then false is returned. However, in case of the second condition code in red it fails.

explain the relationship between equals and hashcode in java

The instanceof operator condition fails to return false if the argument is a subclass of the class Test. Thus, it might violate the symmetry requirement of the contract. The instanceof check is correct only if the class is final, so that no subclass would exist. The first condition will work for both, final and non-final classes. Note that, both these conditions will return false if the argument is null.

However, the first condition should be preferred for better type checking. This class implements the equals method in such a way that it provides equals comparison only for the objects of the same class.

Note that, this is not mandatory. But, if a class decides to provide equals comparison for other class objects, then the other class or classes must also agree to provide the same for this class so as to fulfill the symmetry and reflexivity requirements of the contract. This particular equals method implementation does not violate both these requirements. The lines 14 and 15 actually perform the equality comparison for the data members, and return true if they are equal. Line 15 also ensures that invoking the equals method on String variable data will not result in a NullPointerException.

Whereas, object references can be compared by invoking their equals method recursively. You also need to ensure that invoking the equals method on these object references does not result in a NullPointerException. Here are some useful guidelines for implementing the equals method correctly. This saves time when actual comparison is costly. Use the following condition to check that the argument is not null and it is of the correct type, if not then return false.

If compareTo is not consistent means doesn't return zero, if equals method returns true, it may break Set contract, which is not to avoid any duplicates. What happens if you compare an object to null using equals? When a null object is passed as an argument to equals method, it should return false, it must not throw NullPointerException, but if you call equals method on reference, which is null it will throw NullPointerException.

By the way, if you comparing String literal with another String object then you better call equals method on the String literal rather than known object to avoid NPE, one of those simple tricks to avoid NullPointerException in Java. What is the difference in using instanceof and getClass method for checking type inside equals? This question was asked multiple times, sometimes by looking at your equals and hashCode implementation. Well, key difference comes from the point that instanceof operator returns true, even if compared with subclass e.

Subclass instanceof Superclass is true, but with getClass it's false. By using getClass you ensure that your equals implementation doesn't return true if compared with subclass object. While if you use instanceof operator, you end up breaking symmetry rule for equals which says that if a. Just replace a and b with an instance of Superclass and Subclass, and you will end up breaking symmetry rule for equals method.

Since when compared to null, equals return false and doesn't throw NullPointerException, you can use this property to avoid NPE while using comparing String. Suppose you have a known String "abc" and you are comparing with an unknown String variable str, then you should call equals as "abc".

NullPointerExceptioneven if str is null. On the other hand, if you call str.

So be careful with this. By the way this is one of the Java coding best practices, which Java developer should follow, while using equals method. One of the most classic interview question on equals. It has been asked numerous times during in past decade. I have also covered this question already. These methods become very useful when implementing interactions between several classes in large projects.

In this article, we will talk about the relationship between these methods, their default implementations, and the circumstances that force developers to provide a custom implementation for each of them. Method Definition and Default Implementation equals Object obj: Object that indicates whether some other object passed as an argument is "equal to" the current instance.

The default implementation provided by the JDK is based on memory location — two objects are equal if and only if they are stored in the same 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.

The Contract Between equals and hashcode The default implementation is not enough to satisfy business needs, especially if we're talking about a huge application that considers two objects as equal when some business fact happens.

explain the relationship between equals and hashcode in java

As per the Java documentation, developers should override both methods in order to achieve a fully working equality mechanism — it's not enough to just implement the equals method.