# [E-Lang] Operators #2: Comparison

Ralph Hartley hartley@aic.nrl.navy.mil
Tue, 10 Apr 2001 10:53:28 -0400

```After this discussion I've started to see the wisdom of java's
separation of equals() and compareTo().

The thing is that there are a lot more things with well defined <=>
operations than <, >, etc. . Also, there are always more sensible
definitions of compareTo() than of equals().

The only pitfall of having separate operators is that you need to make
sure they fulfill the consistancy terms of their contract:

x compareTo(y) == 0 iff x equals(y)

By the way, I will definately be a bit upset if the following don't
apply as well:

x equals(y) iff y equals(x)
x equals(x)             I know NaN is a problem here.
if x equals(y) and y equals(z) then x equals(z)

That is equals() is an equivalence, I guess it's just too bad it isn't
on floats. No more exeptions please! And even that may kill you, see below.

Also:

x compareTo(y)  has the oposite sign from y compareTo(x)
if x compareTo(y)  and y compareTo(z) have the same sign, then so does x
compareTo(z)
if x equals(y) then x compareTo(z) has the same sign as y compareTo(z)

If you don't follow these rules you are going to have problems, because
people will assume them (even you will), and get inconsistancies.

For example consider a set or map class based on <=> (equals()), that
is, there are not supposed to be multiple keys that are <=> each other
(I don't know what E or Hydro uses, but java sets are like this).

This can get very unexpected results if the contents of the sets use a
<=> that is not an equivalence. For example {6.2, 6.2} is clearly not a
legal set, but what about {NaN, NaN}? By the definition, it IS legal
since !(NaN<=>NaN), but can anyone guess what will happen if you delete
NaN from it? I can't. No fair looking at the code!

In Java this doesn't cause a problem because (new
Float(Float.NaN)).equals(new Float(Float.NaN)) is true, even though
Float.NaN==Float.NaN is false. Java's equals() DOES have the above
contract, event though == doesn't. Only objects, not floats (small f)
are allowed in java sets. If you allow floats in sets, you have a problem.

Ralph Hartley

```