In the natural world, a person can be a part of a relationship, but a relationship can not be part of a person. Therefore, having Relationship
as a member of Person
is undesirable. Such a setup prevents a Person
from having more than one Relationship
:) and also prevents a Person
from having no Relationship
:(
If we can define a Relationship
as being between 2 people, and 2 people only, then one possible setup would be to have the Relationship
class contain 2 Person
members. If a Relationship
can be between 3 or more people :), then a single List<Person>
member may be more helpful.
I want to be able to assign a Relationship object between two Person objects
If you are trying to discretely ask for dating advice, you have come to the wrong place.
Edit:
If you are trying to get a Relationship
that any given two people are involved in, create a method like this
public Relationship find(List<Relationship> relationships, Person person1, Person person2) {
for (Relationship relationship : relationships) {
if (relationship.getPerson1().equals(person1) && relationship.getPerson2().equals(person2) {
return relationship;
}
if (relationship.getPerson1().equals(person2) && relationship.getPerson2().equals(person1) {
return relationship;
}
}
}
If performance is a concern, use Set<Relationship>
and override the equals()
and hashCode()
methods of Relationship so that two Relationship
objects containing the same people will be considered equal. Then you can do this
Set<Relationship> relationships = new HashSet<Relationship>();
// populate relationships
Relationship delegate = new Relationship(person1, person2);
int hasRelationship = relationships.contains(delegate);