Is Inequality Transitive in Java?

654 Views Asked by At

If I have 3 objects a, b, and c, and I want to check that none of them are equal to each other, I need to check:

if (!a.equals(b) && !b.equals(c) && !a.equals(c)) { // to simplify, assume non-null
    // do something
}

According to the Java docs, for a correctly implemented equals method:

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.

This states that equality is transitive, but what about inequality?

5

There are 5 best solutions below

0
On BEST ANSWER

given a = 5; b = 6; c = 5:

a != b -> true

b != c -> true

a != c -> false

so no, inequality is not transitive.

0
On

It's not transitive. Consider x=1, y=2 and z=1.

0
On

No, of course not.

2 != 3
3 != 2

but

2 == 2
0
On

Well, no. For transitivity you need the condition true for any x, y, z; but if I pick z == x, I would very much hope that

x != y

and y != z

does NOT then imply

x != z

since z is x!

0
On

Inequality is never transitive (if you have 2 elements that are not equal, a and b). Because then you have !a.equals(b) and, because of symmetry !b.equals(a), but because of identitiy you have a.equals(a). So unequality cannot be transitive.