do I need to have hashcode() implemented if I dont use hashtables or hashset with my objects in java

StackOverflow https://stackoverflow.com/questions/21392523

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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top