«
^
»
4.5. The reason for using a zero-returning hashCode
There is one problem which we have not yet considered.
If a client chooses to change a value after it has been put in a collection, the value will no longer be in the right bucket.
So it will not be found if we later search for it.
Rule 1
: a
hashCode
function should not be written in terms of fields that can be changed.
So, if
Date
provides
setYear
,
setMonth
and
setDay
, we should not provide a
hashCode
written in terms of the
iYear
,
iMonth
and/or
iDay
.
This is the reason why we might want to use:
public int hashCode() { return 0; }
A collection class will use one bucket for all the objects we put into the collection.
This means that a method like
contains
will execute more slowly.
It means we can change values after they have been added to the collection.