Why does the Collection interface have equals(Object o)
and hashCode()
, given that any implementation will have those by default (inherited from Object
) ?
hashCode. Returns the hash code value for this collection. While the Collection interface adds no stipulations to the general contract for the Object. hashCode method, programmers should take note that any class that overrides the Object.
The equals() and hashcode() are the two important methods provided by the Object class for comparing objects. Since the Object class is the parent class for all Java objects, hence all objects inherit the default implementation of these two methods.
If two objects are equal(according to equals() method) then the hashCode() method should return the same integer value for both the objects. But, it is not necessary that the hashCode() method will return the distinct result for the objects that are not equal (according to equals() method).
If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.
From the Collection JavaDoc:
While the
Collection
interface adds no stipulations to the general contract for theObject.equals
, programmers who implement theCollection
interface "directly" (in other words, create a class that is aCollection
but is not aSet
or aList
) must exercise care if they choose to override theObject.equals
. It is not necessary to do so, and the simplest course of action is to rely on Object's implementation, but the implementor may wish to implement a "value comparison" in place of the default "reference comparison." (TheList
andSet
interfaces mandate such value comparisons.)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 custom equals method for a collection class that implements neither theList
norSet
interface must return false when this collection is compared to any list or set. (By the same logic, it is not possible to write a class that correctly implements both the Set and List interfaces.)
and
While the Collection interface adds no stipulations to the general contract for the
Object.hashCode
method, programmers should take note that any class that overrides theObject.equals
method must also override theObject.hashCode
method in order to satisfy the general contract for theObject.hashCode
method. In particular,c1.equals(c2)
implies thatc1.hashCode()==c2.hashCode()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With