Your belief is correct. Map structures rely on .equals
to determine if a key already exists in the map or not. By default, object types have instance equality (meaning a.equals(b)
is true if and only if a
and b
point to the same object).
In your case, you probably want two MyString
instances to be equal if the string
field is equal. In this case, you would override equals
with something like:
@Override
public boolean equals(Object other) {
if (other == null) { return false; }
if (!(other instanceof MyString)) { return false; }
MyString m = (MyString)other;
return this.string.equals(m.string);
}
With this, either of the two if statements would return true.
You should also override hashCode
. If you use Eclipse, it can generate these two methods for you quite easily via the Source
menu.