Best way to use contains in an ArrayList in Java?

后端 未结 5 760
甜味超标
甜味超标 2021-01-12 05:51

I have an ArrayList in Java which is made up of a type containing two strings and an integer. I can successfully test if one element of this ArrayList equals another but I f

5条回答
  •  無奈伤痛
    2021-01-12 06:23

    Remember that if you don't override the equals() method, then two objects of your type are only equal if they are the same instance of that object. The ArrayList class uses this method to check that it contains the given object. Also, you need to match the signature exactly, which means that it must take an Object as a parameter and not a Foo.

    Also, the Object contract stipulates that you must override hashCode() whenever you override equals(). If you don't do this, then a HashMap or HashSet won't identify your two objects as being equal, even if the ArrayList does (HashMap checks for identical hashes and then calls equals() on them to check for actual equality). Thus, if ArrayList says that two items aren't equal, then there is no way that HashMap would either. This means that your second solution does not work.

    My recommendation is to check that you actually override equals() and hashCode() properly and that their signatures match the ones in the Object class.

提交回复
热议问题