I have an ArrayList
of Test
objects, which use a string as the equivalency check. I want to be able to use List.contains()
to check whether or not the list contains an object that uses a certain string.
Simply:
Test a = new Test("a");
a.equals("a"); // True
List<Test> test = new ArrayList<Test>();
test.add(a);
test.contains("a"); // False!
Equals and Hash function:
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (!(o instanceof Test)) {
return (o instanceof String) && (name.equals(o));
}
Test t = (Test)o;
return name.equals(t.GetName());
}
@Override
public int hashCode() {
return name.hashCode();
}
I read that to make sure contains
works for a custom class, it needs to override equals
. Thus it's super strange to me that while equals
returns true, contains
returns false.
How can I make this work?
equals
with the same class. – Pastisequals
is suppose to do is wrong, you should be comparingTest
with another instance ofTest
– Dwarf"a".equals(new Test("a")) == false
– Popularly"a".equals(new Test("a")) != new Test("a").equals("a")
is a problem. – PopularlyObject.equals
tacitly requires it, due to the commutative property of non-nullequal
ity. – Centerboard