the answer to this question is probably "impossible", but let me ask independently :)
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 the collection, that is, I have to override the equals method. Not quite a trivial matter, but afloat I will have something like:
@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; }
Sorry for any obvious mistakes by simply typing this out of my head. Now, let's say later, in the application I have ssid, which I received through user input. If I want to compare my ssid with Person, I will need to call something like:
String mySsid = getFromSomewhere(); Person myPerson = getFromSomewhere(); if(myPerson.equals(new Person(mySsid)) doSomething();
This means that I have to create a convenience constructor to create a Person based on ssid (if I don't already have one), and that is also pretty verbose. It would be much easier to just call
myPerson.equals(mySsid)
but if I added string comparisons to the Person equals class, this would break the symmetry property, since String has no idea how to compare itself to Person.
So, finally, the big question is, is there a way to enable such โshorthandโ comparisons using the overriden equals method and without breaking the symmetry rule?
Thanks for any thoughts on this!
EDIT: just to clarify, this is more of an open question than a problem requiring an exact solution. The equations should take into account the cases when I want to extract the Person from the collection. Therefore, it should be possible to do something like this:
List<Person> people = ... people.get(ssid);
It would seem obvious and intuitive to be able to define equality in a class based on a primary key, but I did not find a direct way to do this.