Question

Consider this theoretical scenario:

I have a Person class. I will NOT be doing any look-up operations with this object. I will use them in Arrays, List but not Sets and Maps. But I would like to check if two list of person Object are equal or not.

for example:

List<Person> list1 = new ArrayList<>();
List<Person> list2 = new ArrayList<>();

If I want to check if these lists are equal, System.out.println(list1.equals(list2))

I will have to implement equals method in my Person class. Do I still need to implement Hashcode(). I am not hashing my Person objects into buckets (only for this I require Hashcode()) and so I think it may not be necessary

Was it helpful?

Solution

It is a best practice to implement hashCode if you are overriding equals. Even though you may not be using them as keys right now, you might in the future. If you are providing this class to someone else for use, then you can't know how they'll use it.

I'd recommend you override it and make it a habit when you override one to override the other. It'll help you out in the long run.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top