With respect to 3 contracts mentioned below:
1) Whenever
hashCode()
is invoked on the same object more than once during an execution of an application, thehashCode
method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
From this statement, i understand that, In a single execution of an application, if hashCode()
is used one or more times on same object it should return same value.
2) If two objects are equal according to the
equals(Object)
method, then calling thehashCode()
method on each of the two objects must produce the same integer result.
From this statement, i understand that, to perform the equality operation(in broad scope) in your subclass, There are at least four different degrees of equality.
(a) Reference equality(==), comparing the internal address of two reference type objects.
(b) Shallow structural equality: two objects are "equals" if all their fields are ==.
{ For example, two SingleLinkedList
whose "size" fields are equal and whose "head" field point to the same SListNode
.}
(c) Deep structural equality: two objects are "equals" if all their fields are "equals".
{For example, two SingleLinkedList
that represent the same sequence of "items" (though the SListNodes
may be different).}
(d) Logical equality. {Two examples: (a) Two "Set" objects are "equals" if they contain the same elements, even if the underlying lists store the elements in different orders. (b) The Fractions 1/3 and 2/6 are "equals", even though their numerators and denominators are all different.}
Based on above four categories of equality, second contract will hold good only: if(Say) equals()
method returns truth value based on logical_equality between two objects then hashCode()
method must also consider logical_equality amidst computation before generating the integer for every new object instead of considering internal address of a new object.
But i have a problem in understanding this third contract.
3) IT IS NOT REQUIRED that if two objects are unequal according to the
equals(Object)
method, then calling thehashCode()
method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
In second contract, As we are saying that hashCode()
method should be accordingly[for ex: considering logical_equality before generating integer] implemented, I feel, It is not true to say that, if two objects are unequal according to equals(Object)
then hashCode()
method may produce same integer results as mentioned in third contract? As per the argument in second contract, hashCode()
must produce distinct integer results. One just writing return 42
in hashCode()
is breaking second contract!
please help me understand this point!