Why does the Collection
interface have equals()
and hashCode()
when we can directly use methods from Object
class... why again?
Asked
Active
Viewed 83 times
-2

Paulo Mattos
- 18,845
- 10
- 77
- 85
-
1Because the implementations in the `Collection` API have different semantics. – Stephen C Nov 22 '17 at 14:07
-
2The two exist only to for documentation purposes, so that the general contract for all Collections is specified there. – xs0 Nov 22 '17 at 14:08
-
1@Kayaman, the interface doesn't change the default implementation, and the answer you linked to is not the same question as this.. – xs0 Nov 22 '17 at 14:10
-
@xs0 you're right, I'll reopen. – Kayaman Nov 22 '17 at 14:25
1 Answers
1
You’re thinking of terms of compilation. Java SE is an object-oriented library; methods are defined as part of a contract, not just to declare methods available to other code wen compiling.
Collection.equals refines the contract of Object.equals with additional stipulations:
The general contract for the
Object.equals
method states that equals must be symmetric (in other words,a.equals(b)
if and only ifb.equals(a)
). The contracts forList.equals
andSet.equals
state that lists are only equal to other lists, and sets to other sets. Thus, a customequals
method for a collection class that implements neither theList
norSet
interface must returnfalse
when this collection is compared to any list or set.

VGR
- 40,506
- 4
- 48
- 63