Importance of Equals and Hashcode in Apex

Recently while doing code review, I found that all developers should have fundamental understanding of “Why we should implement always Equals and Hashcode in Apex?”In this post, I am going to share my knowledge with few examples to understand the importance of Equals and Hashcode in Apex.Apex provides you an option to define an equal method in your custom types. This Equals method along with Hashcode is must when you are going to use your custom types in Sets and as Map keys. I would recommend to make this approach (Implementation of Equals and Hashcode) as best practice. Equality operator (==) is going to use the Equals operator if it is defined.Why we need this Equals method?Let me start with one example to show you the problem if Equals method is not implemented. Below is the custom type I am having -Now below is the test class to compare two instances of MyCustomType. Both the instances of MyCustomType is having myField value set to 10. So my expectation is that when I will compare both the instances, they should return true. Let’s see what will happen. Below is the test class.But unfortunately, below is what you will get -You see our test class is failing. Do you know the reason? Let me tell you the reason. The reason for this comparison to fail is that I don’t have the Equals method in...

Read More