Wednesday, August 28, 2013

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 equality of objects, primarily inside hash based collections such as Hashtable and HashMap. Both equals() and hashCode() are defined in java.lang.Object class and there default implementation is based upon Object information e.g. default equals() method return true, if two objects are exactly same i.e. they are pointing to same memory address, while default implementation of hashcode method return int and implemented as native method. Similar default implementation of toString() method, returns type of class, followed by memory address in hex String. It's advised to override these method, based upon logical and business rules e.g. String overrides equals to check equality of  two String based upon content, we have also seen and example implementation of equals() and hashCode for custom classes. Because of there usefulness and usage, they are also very popular in various level of Java Interviews, and In this tutorial, I am going to shared some of the really interesting questions from equals() and hashCode() method in Java. This question not only test your concept on both method, but also gives an opportunity to explore them more.


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 also suggest to read Effective Java Items on equals() and hashCode() to fill your gaps on knowledge of this two critical 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.

When you are writing equals() method, which other method or methods you need to override?
hashcode, is the right answer. Since equals and hashCode has there contract, so overriding one and not other, will break contract between them. By the way this question can lead on interesting discussion, if Interviewer likes to go on deep e.g. he may ask about what are those contracts, what happens if those contracts breaks etc. I like to give an example How equals and hashcode are used in hash based collections e.g. Hashtable, that leaves positive impression more often. You can also mention about compareTo() here to score some additional point, this method should also needs to be consistent with equals, which is another interesting question in our list.

Can two object which are not equal have same hashCode?
YES, two object, which are not equal by equals() method can still return same hashCode. By the way, this is one of the confusing bit of equals and hashcode contract.

How does get() method of HashMap works, if two keys has same hashCode?
This is the follow-up of previous interview questions on equals and hashcode, in fact some time this leads to discussion of the earlier point. When two key return same hashcode, they end-up in 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.

Where have you written equals() and hashCode in your project?
This is to see, if 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 form your domain.

Suppose your Class has an Id field, should you include in equals()? Why?
This question is asked to one of my reader 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 database.

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, the it may break Set contract, which is not to avoid any duplicates.

What happens if you compare an object with null using equals()?
When a null object is passed as 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 than you better call equals() method on literal rather than known object to avoid NPE, one of those simple tricks to avoid NullPointerException in Java.

What is difference in using instanceof and getClass() method for checking type inside equals?
This question was asked multiple times, sometime by looking at your equals() and hashCode implementation. Well key difference comes from point that instanceof operator returns true, even if compared with sub class e.g. Subclass instanceof Super class is true, but with getClass() it's false. By using getClass() you ensure that your equals() implementation doesn't return true if compared with sub class 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 instance of Super class and Sub class, and you will end up breaking symmetry rule for equals() method.

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.

What is difference between "==" and equals() method in Java?
One of the most classical interview question on equals(). It has been asked numerous times during in past decade. I have also covered this question already. See here for detailed discussion on how it affect equality checking of String and Integer in auto boxing world.

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

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

Post a Comment