I'm struggling with Java and need some help with 1-1 associations. Sorry if I'm wording something wrong, I don't know how to word it properly in English.
I want to connect both partner1 and partner2 using one call. Before the call, partner1 and partner2 is not connected, but after, they are. I can't wrap my head around and have been stuck for hours.
Here is what I have so far:
public class Partner {
private String name;
private Partner partner;
public String getName() {
return this.name;
}
public Partner getPartner() {
return this.partner;
}
public Partner(String name) {
this.name = name;
}
public void setPartner(Partner person) {
if (this == person) {
throw new IllegalArgumentException("You can not marry yourself!");
} else {
this.partner = person;
}
}
@Override
public String toString() {
return "Partner [name=" name ", partner=" partner "]";
}
public static void main(String[] args) {
Partner p1 = new Partner("Mickey");
Partner p2 = new Partner("Minnie");
p1.setPartner(p2);
System.out.println(p1.getPartner());
}
}
CodePudding user response:
You need to do the other association too, but don't use person.setPartner(this)
because it would call it then the other and you'll go deep into recursion until a StackOverflowError
public void setPartner(Partner person) {
if (this == person) {
throw new IllegalArgumentException("You can not marry yourself!");
} // else isn't mandatory as code execution whould stop if first branch taken
this.partner = person;
person.partner = this;
}
For the same reason, you may use partner.name
. If you keep partner
, it' would call it's toString
which would call it's partner toString
, then road to StackOverflowError
@Override
public String toString() {
return "Partner [name=" name ", partner=" partner.name "]";
}