我正在练习Java,但遇到了问题。我想使setPartner方法动态化,在将p1和p2作为伙伴连接的情况下,如果我决定在p1和p3上调用setPartner(),则p2将断开连接。我该如何实现?
public class Partner {
private final String name;
private Partner partner;
private Partner unlinked;
public Partner(String name) {
this.name = name;
partner = null;
}
public String getName() {
return name;
}
public Partner getPartner(){
if (partner != null){
return partner;
}
else {
return null;
}
}
public void setPartner(Partner p1, Partner p2){
if(p1 == null || p2 == null){
p1.partner = null;
p2.partner = null;
}
else{
p1.partner = p2;
p2.partner = p1;
System.out.println(unlinked);
}
}
public static void main(String[] args) {
Partner p1 = new Partner("JohnP1"); // Create Partner Objects
Partner p2 = new Partner("JaneP2");
Partner p3 = new Partner("JacksonP3");
// System.out.println(p1.getName()); // Test names
// System.out.println(p2.getName());
p1.setPartner(p1,p2); // set partners and test if relation works
p1.setPartner(p1,p3);
System.out.println(p2.getPartner().getName());
//p1.setPartner(p1, null); // test for null
//System.out.println(p2.getPartner().getName());
}
}
答案 0 :(得分:3)
您可以执行以下操作:
public class Partner {
private final String name;
private Partner partner;
public Partner(String name) {
if (name == null) throw new NullPointerException();
this.name = name;
}
public Partner getPartner() {
return partner;
}
public void setPartner(Partner p) {
// this is critical, or else we'll call each other forever in a loop
if (partner == p) {
// we're already partners with p; nothing to do
return;
}
if (partner != null) {
// already have a partner; tell them we're leaving, directly
partner.partner = null; // (we don't want them to call us back)
}
partner = p;
if (p != null) {
// new partner; let them know about us
p.setPartner(this);
}
}
}
最初它是没有伙伴创建的。我看不到unlinked
字段或您在getPartner
中进行的测试。所有工作都在setPartner
中完成;有关详细信息,请参阅此处的评论。
更新:
当我们将合伙人的合伙人设置为null
告诉他们我们要离开时,我们必须直接这样做,而不是通过调用他们的set方法,否则他们会立即回电话告诉他们他们要离开我们了。我敢肯定,与人际关系的任何关系纯属巧合。该答案的早期版本存在严重的错误。
答案 1 :(得分:1)
当您连接两个伙伴时,它们是双向连接的。例如,如果连接P1 + P3,则P1.partner == P3和P3.partner == P1。现在,如果您连接P1 + P2,则P1.partner == P2和P2.partner == P1但P3.partner == P1来自先前的连接,因此必须将P3.partner设置为null。为了将P3.partner设置为null,P1.partner.partner = null可以解决问题。
public void setPartner(Partner p1, Partner p2){
if(p1 != null && p2 != null){
if(p1.partner !=null) p1.partner.partner = null;
if(p2.partner !=null) p2.partner.partner = null;
p1.partner = p2;
p2.partner = p1;
System.out.println(unlinked);
}
}