当人员1与人员3成为合作伙伴时,人员2不再将人员1作为合作伙伴,人员4不再将人员3作为合作伙伴。我该如何解决这个问题?
public class Person {
private String name;
private Person partner;
public Person(String name){
this.name = name;
}
public void setPartner(Person partner){
this.partner = partner;
partner.partner = this;
}
public static void main(String[] args) {
Person one = new Person("1");
Person two = new Person("2");
Person three = new Person("3");
Person four = new Person("4");
one.setPartner(two);
three.setPartner(four);
one.setPartner(three);
//Person two is still partner with person 1
//and person four is still partner with person 3
}发布于 2010-05-20 00:28:15
public void setPartner(Partner b) {
// Special case, otherwise we'll have troubles
// when this.partner is already b.
if (this.partner == b) return;
if (this.partner != null) {
this.partner.partner = null;
}
this.partner = b;
// Make sure that the new partner has the right partner.
// This will make sure the original b.partner has its
// partner field nullified.
// Note that if we don't have the special case above,
// this will be an infinite recursion.
b.setPartner(this);
}发布于 2010-05-20 00:09:40
public void setPartner(Person partner){
if (this.partner != null) {
this.partner.partner = null; // Reset the partner of the old partner.
}
this.partner = partner; // Assign new partner.
this.partner.partner = this; // Set the partner of the new partner.
}发布于 2010-05-20 00:09:23
我认为把它作为setPartner的第一行应该行得通:this.partner.partner = null;
当然,您必须检查this.partner是否为null。
https://stackoverflow.com/questions/2867304
复制相似问题