Transitive nature of equals method

前端 未结 4 1189
一个人的身影
一个人的身影 2020-12-09 15:23

The contract for equals(object) method specifies 4 properties to follow: Reflexive, Symmetric, Transitive and Consistent. While I understand the danger of not f

4条回答
  •  渐次进展
    2020-12-09 16:12

    Assume three objects a,b,c with

    a == a, b == b, c == c (reflexive)
    a == b, b == a
    b == c, c == b
    a != c, c != a
    

    (Pseudocode, x == y stands for x.equals(y)).

    Now, let's add the objects to a set:

    Set s = new HashSet(); // Set implementation doesn't matter
    s.add(b); // s = [b]
    s.add(a); // s doesn't change, because a == b
    s.add(c); // s doesn't change, because c == b
    

    In contrast, if we were to add them in a different order:

    Set s = new HashSet();
    s.add(a); // s = [a]
    s.add(b); // s doesn't change, because b == a
    s.add(c); // s = [a,c], because c != a
    

    That is clearly counter-intuitive and doesn't match the behavior one would expect of a set. For example, it would mean that the union of two sets (i.e. the state of s after s.addAll(someOtherSet)) could depend on the implementation (order of elements) of someOtherSet.

提交回复
热议问题