Friday, August 6, 2021

10 Equals and HashCode Interview Questions in Java

Equals and HashCode methods in Java are two fundamental methods from java.lang.Object class, which is used to compare the equality of objects, is primarily inside hash-based collections such as Hashtable and HashMap. Both equals() and hashCode() are defined in java.lang.Object class and their default implementation is based upon Object information e.g. default equal () method return true if two objects are exactly the same i.e. they are pointing to the same memory address while default implementation of hashcode method return int and is implemented as a native method. A similar default implementation of the toString() method, returns the type of class, followed by the memory address in hex String.

It's advised to override these methods, based on logical and business rules e.g. String overrides equals to check equality of  two String based upon content, we have also seen and the example implementation of equals() and hashCode for custom classes. Because of their usefulness and usage, they are also very popular in various level of Java Interviews, and

In this tutorial, I am going to share some of the really interesting questions from equals() and hashCode() method in Java. This question not only tests your concept on both method but also gives an opportunity to explore them more.

By the way, if you are preparing for Java Interviews then I also suggest taking a look at the Java Programming Interview Exposed book, one of the best books to prepare for Java programming interview. You will learn about everything you could expect in Java interviews.




Equals and HashCode Interview questions in Java

equals and hashcode method interview questions in JavaHere is my list of 10 interesting questions on both of these methods.  I have seen, programmer struggles to write equals() and hashCode() by hands, for a rich class, which contains different data types e.g. int, float, date, etc. 

Reading those items and trying examples will give you enough confidence to face any question on equals and hashCode methods. I also suggest reading Effective Java Items on equals() and hashCode() to fill your gaps in knowledge of these two critical methods.


1. When you are writing equals() method, which other method or methods do you need to override?

hashcode is the right answer. Since equals and hashCode have their contract, so overriding one and not other will break the contract between them. By the way this question can lead to an interesting discussion if Interviewer likes to go on deep e.g. he may ask what are those contracts, what happens if those contracts break etc. 

I like to give an example How equals and hashcode are used in hash-based collections e.g. Hashtable, which leaves a positive impression more often. You can also mention about compareTo() here to score some additional points, this method should also need to be consistent with equals, which is another interesting question on our list.

Equals and hashcode interview questions answers java

2. Can two objects which are not equal have the same hashCode?

YES, two objects, which are not equal to equals() method can still return same hashCode. By the way, this is one of the confusing bit of equals and hashcode contract. See Core Java, Volume 1 9th Edition by Cay S. Horstmann for  more details.

equals and hashcode interview questions in Java



3. How does get() method of HashMap works, if two keys have the same hashCode?

This is the follow-up of previous interview questions on equals and hashcode, in fact, sometimes this leads to a discussion of the earlier point. When two key return same hashcode, they end up in the same bucket. Now, in order to find the correct value, you used keys.equals() method to compare with key stored in each Entry of linked list there. Remember to point out keys.equals() method, because that's what interviewer is looking for. You can also see here for full list of interview question on Java HashMap.


4. Where have you written equals() and hashCode in your project?

This is to see if the developer has even written these methods or not. Of course, almost all of Java programmer are exposed to this, you can point out value objects, Hibernate entities from your domain, where you have overridden equals and hashCode. Always gives examples from your domain and from your project, rather than a trivial example from a test program, because if Interviewer is asking this question, it means he is interested in examples from your domain.


5. Suppose your Class has an Id field, should you include in equals()? Why?

This question is asked to one of my readers as Hibernate Interview question, well including id is not a good idea in equals() method because this method should check equality based upon content and business rules. Also including id, which is mostly a database identifier and not available to transient object until they are saved into the database.


6. What happens if equals() is not consistent with compareTo() method?

This is an interesting questions, which asked along with equals() and hashCode() contract. Some java.util.Set implementation e.g. SortedSet or it's concrete implementation TreeSet uses compareTo() method for comparing objects. 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.


7. 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. That’s why it’s better to use == operator for comparing null e.g. if(object != null) object.equals(anohterObject). 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.




8. 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.g. 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.equals(b) is true than b.equals(a) should also be true. Just replace a and b with an instance of Superclass and Subclass, and you will end up breaking symmetry rule for equals() method.


9. How do you avoid NullPointerException, while comparing two Strings in Java?

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".equals(str), this will not throw Exception in thread Main: java.lang.NullPointerException, even if str is null. 

On the other hand, if you call str.equals("abc"), it will throw NPE. 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.


10. What is the difference between "==" and equals() method in Java?

One of the most classic interview questions on equals(). It has been asked numerous times during in past decade. I have also covered this question already. See here for a detailed discussion on how it affect equality checking of String and Integer in the autoboxing world.

equals vs == in Java



That's all on this list of Java Interview Questions on Equals and HashCode methods in Java. It's one of the fundamental concepts of Java programming language, but yet it has several subtle things, which is unknown to many Java programmers. I strongly suggest getting yourself really good on equals(), hashCode(), compareTo() and compare() methods, not only to do well on Java Interviews but also to write correct code in Java.

More questions:
Top 130+ Java Interview Questions from Last 5 years (read more)
50+ Java Threading Questions from Last 3 years (the list)
50+ Programming Phone Interview Questions with answers (read)


6 comments :

Anonymous said...

as we know HashMap use hashCode() method to get the hashcode of key i.e. key.hashCode(). I can put null in the key that will be stored in HashMap but null.hashCode() should throw NullPointerException ?

Anonymous said...

Here is a tricky question I was asked on Equals, What is the value of following expression and Why?

Integer.valueOf(1).equals(Long.valueOf(1))

Answer is false, because even though numeric value is same, they are of different types e.g. Integer and Long because Integer.valueOf(1) will return Integer, while Long.valueOf(1) will return Long, Since equals method of Integer class checks for type using intstanceof operator, this will return false :

public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

SARAL SAXENA said...

@Javin nice article but I want to add few points in it that will bring more clearity..



It is not always necessary to override hashcode and equals. But if you think you need to override one, then you need to override both of them. Let's analyze what whould happen if we override one but not the other and we attempt to use a Map.

Say we have a class like this and that two objects of MyClass are equal if their importantField is equal (with hashCode and equals generated by eclipse)

public class MyClass {

private final String importantField;
private final String anotherField;

public MyClass(final String equalField, final String anotherField) {
this.importantField = equalField;
this.anotherField = anotherField;
}

public String getEqualField() {
return importantField;
}

public String getAnotherField() {
return anotherField;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((importantField == null) ? 0 : importantField.hashCode());
return result;
}

@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final MyClass other = (MyClass) obj;
if (importantField == null) {
if (other.importantField != null)
return false;
} else if (!importantField.equals(other.importantField))
return false;
return true;
}

}

Override only hashCode

Imagine you have this

MyClass first = new MyClass("a","first");
MyClass second = new MyClass("a","second");

If you only override hashCode then when you call myMap.put(first,someValue) it takes first, calculates its hashCode and stores it in a given bucket. Then when you call myMap.put(second,someOtherValue) it should replace first with second as per the Map Documentation because they are equal (according to our definition).

But the problem is that equals was not redefined, so when the map hashes second and iterates through the bucket looking if there is an object k such that second.equals(k) is true it won't find any as second.equals(first) will be false.

Override only equals

If only equals is overriden, then when you call myMap.put(first,someValue) first will hash to some bucket and when you call myMap.put(second,someOtherValue) it will hash to some other bucket. So, although they are equal, as they don't hash to the same bucket (different hashCode) the map can't realize it and both of them stay in the map.


SARAL SAXENA said...

@ Javi here in this article we can also add.


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.lang.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.

Anonymous said...

@SARAL SAXENA
Did you copy-paste your comments from following ?? LOL !!!
http://www.xyzws.com/javafaq/why-always-override-hashcode-if-overriding-equals/20

Unknown said...

In case of null as a key hashcode() is not called map put this null key as index[0].as it's very clear that only one null key can be stored in a map.
So when you call get(key) it retrieves from index[0] without calling hashcode().

Arvind

Post a Comment