ArrayList not using the overridden equals

后端 未结 11 1424
误落风尘
误落风尘 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 15:10

    Although not answering your question, many Collections use hashcode(). You should override that too to "agree" with equals().

    Actually, you should always implement both equals and hashcode together, and they should always be consistent with each other. As the javadoc for Object.equals() states:

    Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

    Specifically, many Collections rely on this contract being upheld - behaviour is undefined otherwise.

提交回复
热议问题