What you are checking for is not necessarily a "problem": equals()
is declared in the Object
class, and takes and Object
as its parameter. Classes override this method, and their implementation may well allow an object of a different class to "equal" the target object.
I have done this a few times myself, for example for allowing an object to "equal" another object if the other object (say a String) matches the key field of the target:
class MyClass {
private String id;
public boolean equals(Object obj) {
// Compare as if "this" is the id field
return id.equals(obj instanceof MyClass ? ((MyClass)obj).id : obj);
}
public int hashCode() {
return id.hashCode(); // so hashCode() agrees with equals()
}
}
It's actually pretty handy, because the following code will work as desired:
List<MyClass> list = new ArrayList<MyClass>();
// collection methods will work with instances:
list.contains(someInstance);
list.remove(someInstance);
list.indexOf(someInstance);
// and with keys!
// handy if you can only get the key, for example from a web url parameter
list.contains("somekey");
list.remove("somekey");
list.indexOf("somekey");