1

I am in a bit of confusion. Suppose I have class A and some List<A> in some other class B.

So, because I am using a list, duplicates are allowed. Because duplicates are allowed (that means no comparison needed), do I have to override method equals() and hashCode() in class A?

So the emphasis here is on List (duplicates allowed - no need for comparison).

And I should override these 2 methods when I am using Set (duplicates NOT allowed - we need to define how objects will be compared)? (99% sure this is correct answer, just want to check it and make sure I got 100% correct answer for both: List and Set)

Note: I did not find answer on stack because no one asked excact same thing with using lists and duplicates allowed.

Cluv
  • 25
  • 5
  • The question about `Set` should be a separate post, not bundled into this question. – Louis Wasserman Sep 30 '20 at 20:40
  • 2
    Have you checked out those two? [Why do I need to override the equals and hashCode methods in Java?](https://stackoverflow.com/q/2265503/12323248), [What issues should be considered when overriding equals and hashCode in Java?](https://stackoverflow.com/q/27581/12323248) – akuzminykh Sep 30 '20 at 20:43

1 Answers1

3

If you do not plan to ever compare any A objects to each other -- meaning you're neither using a Set, nor List methods like indexOf or contains -- then you do not need to implement equals or hashCode.

However, if you do ever intend to use indexOf or contains -- or if you plan to test your code, e.g. by asserting that the A in the List is equal to some expected A -- then you do need to implement equals, and it is poor practice to implement equals without also implementing hashCode. You don't need a good implementation of hashCode, but you should have one.

Louis Wasserman
  • 172,699
  • 23
  • 307
  • 375