‘equals()’ and ‘hashCode()’ are context-sensitive
equals()
and hashCode()
implementations should rely only on an internal object state. Making them dependent on other objects, context of use and other external conditions conflicts with the general contracts of consistency:
“For any reference values
x
andy
, multiple invocations ofx.equals(y)
consistently returntrue
or consistently returnfalse
” [*]
“Whenever it is invoked on the same object more than once during an execution of a Java application, the
hashCode
method must consistently return the same integer” [*]
Violating those contracts may cause all kinds of weird and unpredictable behavior.
A known example of this antipattern is equals()
and hashCode()
in java.net.URL
implementation where they are depending on information returned by a domain name server, rather than on actual stored URL data.
See also:
[…] It is incostistent […]
Comparing URLs with ‘URL.equals()’ « Java AntiPatterns
November 24, 2007 at 6:53 am
Please give due credit to Joshua Baloch before copy/pasting.
Zahid
March 7, 2012 at 4:37 pm
Do you mean Bloch? So, could you point me to a sentence which has actually been copypasted from any of his work?
Alex
March 7, 2012 at 5:28 pm