문제

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?

도움이 되었습니까?

해결책

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

a != b -> true

b != c -> true

a != c -> false

so no, inequality is not transitive.

다른 팁

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

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.

No, of course not.

2 != 3
3 != 2

but

2 == 2

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!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top