Search code examples
javaequalsinequalitytransitivity

Is Inequality Transitive in Java?


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?


Solution

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

    a != b -> true

    b != c -> true

    a != c -> false

    so no, inequality is not transitive.