英文:
Overriding equals() when using Lists in Java
问题
我有点困惑。假设我有一个类A和一些List<A>
在另一个类B中。
所以,因为我正在使用一个列表,允许重复。因为允许重复(这意味着不需要比较),我是否需要在类A中重写**equals()和hashCode()**方法?
所以重点在于List(允许重复 - 不需要比较)。
当我使用Set<A>时,我应该重写这两个方法吗(不允许重复 - 我们需要定义对象如何比较)?(99%确定这是正确答案,只是想检查一下,并确保我对List和Set的答案都百分之百正确)
注意:我没有在堆栈上找到答案,因为没有人使用相同的方式提出问题,即使用列表并允许重复。
英文:
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<A> (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.
答案1
得分: 3
如果您不打算对任何 A
对象进行比较,也就是说,您既不使用 Set
,也不使用 List
的 indexOf
或 contains
方法,那么您就不需要实现 equals
或 hashCode
。
然而,如果您确实打算使用 indexOf
或 contains
— 或者如果您计划通过断言 List
中的 A
是否等于某个预期的 A
来测试您的代码 — 那么您就需要实现 equals
,并且实现 equals
而不实现 hashCode
是不良实践。您不需要一个 良好的 hashCode
实现,但您应该有一个。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论