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
Most likely, you have simply forgotten to override equals() and hashCode() in your type. equals() is what contains() checks for.
From the Javadoc:
Returns
trueif this list contains the specified element. More formally, returnstrueif and only if this list contains at least one elementesuch 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.