0

I understand the contract between hashcode() and equals(). What I don't understand is that should I include all the fields of my class(bean) while calculating the same? e.g. I need to use my bean object in hash based collection and requires sorting. The bean class contains ~25 fields.

Is it necessary to consider all of its field while overriding HashCode() and euqals()?

Diganta
  • 245
  • 1
  • 7
  • 21
  • 4
    No. Only those fields which are necessary for determining "identity" (for hash code) - and as for equals, that is up to you. The default Object#equals only tests reference equality. – Elliott Frisch Jan 06 '17 at 04:50
  • @Elliot As per my understanding the best practice is to use the same fields in hashcode() and equals(). – Diganta Jan 06 '17 at 05:00
  • 1
    Do you understand the difference between *absolutely necessary* and *best practice*? What are you asking here? – Elliott Frisch Jan 06 '17 at 05:02
  • 2
    Just an advice, you can use lombok's annotation [@EqualsAndHashCode](https://projectlombok.org/features/EqualsAndHashCode.html) and put there only necessary fields for `equals` and `hashCode` – Dmitry Gorkovets Jan 06 '17 at 05:14
  • No. It depends on how you want make your object identity. But to do that you should over ride `equals()` and `hashcode()` methods based on at least with one field. – Ramesh Papaganti Jan 06 '17 at 07:11
  • @MWiesner Can't agree with you. – Diganta Jan 06 '17 at 08:54

2 Answers2

1

It is definitely not mandatory to use all members, but I suggest keep all variables that change from object to object. There can be constant or even variable that might not change much from object to object you can remove those, if there are other unique fields.

I have even seen in one of the project, using only "id" field(unique from object to object) to calculate hashcode.

Edit: liked the suggestion from Dimitry in comment section, if in case you want to remove fields do try: https://projectlombok.org/features/EqualsAndHashCode.html Looks cleaner

Bikas Katwal
  • 1,895
  • 1
  • 21
  • 42
0

You shouldn't override equals nor hashCode methods unless is absolutely necessary.

When you need to do so, try to use only the fields that make your objects "unique" among them.

In order to sort the objects you can take a look at Comparator or Comparable interfaces which you can use to compare objects given a particular field or a set of fields.

alayor
  • 4,537
  • 6
  • 27
  • 47