Thursday 10 March 2016

Be Careful while overriding hashCode() and equals() methods inside an Inner class

I know couple of questions coming into your mind before coming here.
    1. What is the new or different things while overriding hashCode() and equals() methods inside an inner class?
    2. Is there really any difference while overriding in a normal class and an inner class?

To answer these questions, let's see an example :

 Output








Here observe the output carefully, we have added 4 task executors into the set and then executing all one by one. But only 2 executors are executed. Because here taskExecutor1 and taskExecutor3 having same data/state and the hashCode() and equals() method identify both the objects as equal. Similarly for  taskExecutor2 and taskExecutor4 also.

Even though the state of the executor objects taskExecutor1 and taskExecutor2 are same, but they are associated with 2 different outer class objects service1 and service2 having different state/data. As a result somewhere if the inner class object depends on the outer class object's state, it may behave different. So the inner class objects should not be treated as equal objects if they are associated with different outer class objects regardless of its own state.

Let's modify the overriden equals() method inside the inner class in such a way that it should check the equality of the outer class objects also.

So while overriding equals() method inside inner class, it is most important to check the equality of the objects of the enclosed outer class. 

Output with the modified code :
 Note : If the outer class have non-static member(s), then it is mandatory to check the equality of the objects of the enclosing outer class.


Thank You for Visiting the blog. Please feel free to share yout comment/suggestion.