Hi,
the answer to this question is probably "not possible", but let me ask regardless :)
Assuming we have a very simple JAVA class that has a primary key, for example:
class Person {
String ssid;
String name;
String address;
...
}
Now, I want to store people in a collection, meaning I will have to override the equals method. Not a completely trivial matter, but on a bare basis I will have something along the lines of:
@Override
public boolean equals (Object other) {
if(other==this) return true;
if(!other.getClass().equals(this.getClass()) return false;
Person otherPerson = (Person)other;
if(this.ssid.equals(otherPerson.getSsid()) return true;
}
Excuse any obvious blunders, just typing this out of my head. Now, let's say later on in the application I have a ssid I obtained through user input. If I want to compare my ssid to a Person, I would have to call something like:
String mySsid = getFromSomewhere();
Person myPerson = getFromSomewhere();
if(myPerson.equals(new Person(mySsid)) doSomething();
This means I have to create a convenience constructor to create a Person based on ssid (if I don't already have one), and it's also quite verbose. It would be much nicer to simply call
myPerson.equals(mySsid)
but if I added a string comparison to my Person equals class, that would break the symmetry property, since the String hasn't got a clue on how to compare itself to a Person.
So finally, the big question, is there any way to enable this sort of "shorthand" comparisons using the overriden equals method, and without breaking the symmetry rule?
Thanks for any thoughts on this!