-2

Why does the Collection interface have equals() and hashCode() when we can directly use methods from Object class... why again?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
  • 1
    Because the implementations in the `Collection` API have different semantics. – Stephen C Nov 22 '17 at 14:07
  • 2
    The 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 Answers1

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 if b.equals(a)). The contracts for List.equals and Set.equals state that lists are only equal to other lists, and sets to other sets. Thus, a custom equals method for a collection class that implements neither the List nor Set interface must return false when this collection is compared to any list or set.

VGR
  • 40,506
  • 4
  • 48
  • 63