当人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
   }

最佳答案

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);
}

关于java - 对象引用案例研究,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2867304/

10-14 08:58