Pages

April 06, 2016

#Java: Part 4-Core Java Interview Questions and Answers (HashCode & equals())

> > Part 3-Core Java Interview Questions and Answers

When you are writing equals() method, which other method or methods you need to override? 
The right answer is hashCode(). Since equals and hashCode has there contract, so overriding one and not other, will break contract between them. Interviewer may ask about what are those contracts, what happens if those contracts breaks etc.

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.

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) 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.
 
Where have you written equals() and hashCode in your project?
This question is asked just 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.

ALSO READ: Java Collections Interview Questions and Answers

Suppose your Class has an Id field, should you include in equals()? Why?
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?
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(anotherObject).

If you are 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?
instanceof operator which 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.

Does not overriding hashCode() method has any performance implication?
  • A poor hash code function will result in the frequent collision in HashMap which eventually increases the time for adding an object into Hash Map. 
  • From Java 8 onwards though collision will not impact performance as much as it does in earlier versions because after a threshold the linked list will be replaced by a binary tree, which will give you O(logN) performance in the worst case as compared to O(n) of a linked list.

ALSO CHECKCore Java Interview Questions And Answers

-K Himaanshu Shuklaa..

1 comment:

  1. I can put null in the key that will be stored in HashMap but null.hashCode()should throw NPE?

    ReplyDelete