Reputation: 176
EDIT: the question is why cant I use ".contains" (override .equals() in the object) to compare object attributes (a string) instead of comparing the object itself. Thanks JB: Turns out I was confusing overriding compareTo() with overriding equals()
EDIT: QUESTION REDEFINED:
Why cant I override equals to compare strings in my object:
public boolean equals(Object obj){
...
if(obj instanceof String){
String testString = (String) obj;
...
}
...
}
Or even overload for that matter:
public boolean equals(String stringObj){
...
}
I read somewhere that the compiler doesn't use logic to decide this, it uses types. So if I then call myObj.equals(stringOne + "_" + stringTwo)
shouldn't this work as it knows a string is being passed?
Thanks,
Steve.
Upvotes: 0
Views: 284
Reputation: 691765
Why this code doesn't make sense:
a < b
is true, then b > a
must be true. You can compare an instance of your class with String, but a String can't compare with an instance of your custom class. You're thus breaking the contract of ComparablecompareTo()
to check if an element exists or not. It uses equals()
.Set
.Do the right thing, and use a HashSet. Make sure CustomClass implements equals()
and hashCode()
correctly. You could also use a HashMap<CustomClassKey, CustomClass>
, where CustomClassKey is a simple class containing the two fields identifying your CustomClass instances.
Upvotes: 1