ArrayList not using the overridden equals

后端 未结 11 1620
误落风尘
误落风尘 2021-02-08 14:13

I\'m having a problem with getting an ArrayList to correctly use an overriden equals. the problem is that I\'m trying to use the equals to only test for a single key field, and

11条回答
  •  忘掉有多难
    2021-02-08 14:52

    According to the JavaDoc of List.contains(o), it is defined to return true

    if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

    Note that this definition calls equals on o, which is the parameter and not the element that is in the List.

    Therefore String.equals() will be called and not InnerClass.equals().

    Also note that the contract for Object.equals() states that

    It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

    But you violate this constraint, since new TestClass("foo", 1).equals("foo") returns true but "foo".equals(new TestClass("foo", 1)) will always return false.

    Unfortunately this means that your use case (a custom class that can be equal to another standard class) can not be implemented in a completely conforming way.

    If you still want to do something like this, you'll have to read the specification (and sometimes the implementation) of all your collection classes very carefully and check for pitfalls such as this.

提交回复
热议问题