Best way to use contains in an ArrayList in Java?

后端 未结 5 774
甜味超标
甜味超标 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:02

    Most likely, you have simply forgotten to override equals() and hashCode() in your type. equals() is what contains() checks for.

    From the Javadoc:

    Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

    Since the default implementation of equals tests for reference equality, it's not suitable for custom data types like this one.

    (And if you didn't override equals and hashCode, using your types as keys in a HashMap would be equally futile.)


    Edit: Note that to override, you must provide the exact signature.

    class MyDataType {
        public boolean equals(MyDataType other) { // WRONG!
            ...
        }
        public boolean equals(Object other) { // Right!
            ...
        }
    }
    

    This is a very strong argument for using the @Override annotation; the first example would have failed at compile time if annotated with @Override.

提交回复
热议问题