# Value equality

John Rose john.r.rose at oracle.com
Thu May 19 00:18:04 UTC 2016

```On May 18, 2016, at 4:29 PM, forax at univ-mlv.fr wrote:
>
>> On May 18, 2016, at 3:58 PM, John Rose <john.r.rose at oracle.com> wrote:
>>
>> Yes but if CE is a subset of OE then their union is just OE.  (Viewing relations as sets of pairs.)  In your example that is the case. Any .equals method must extend CE or it breaks the .equals contract.
>>
>> – John
>
> It doesn't seem practical to me to add this constraint:
> - there is no way to enforce that constrain but to run the code.
> - it will make the retrofitting of a class to a value class hazardous.
>
> Rémi

Maybe I was unclear.  By "extend CE" I mean "it must agree with CE where CE reports equality", or "it must implement a relation which is a superset of CE".

Or, to put it in code:  Given V a, compute V b = a (as a simple copy), and then assert(a.equals(b) && b.equals(a)).

Or, in the language of relations, every .equals method is reflexive.

It is actually hard to write an .equals method that breaks this contract.  Your example keeps the contract.

https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-
> Indicates whether some other object is "equal to" this one.
> The equals method implements an equivalence relation on non-null object references:
>
> 	• It is reflexive: for any non-null reference value x, x.equals(x) should return true.
> 	• It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
> 	• It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
> 	• It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
> 	• For any non-null reference value x, x.equals(null) should return false.

So is the description of (what we now call) CE for references:

> The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

The property I would rely on to optimize back-to-back .equals calls in P2 is the "consistent" property above, which implies that x.equals(y)||x.equals(y) can be replaced by x.equals(y).

— John
```