0

我只是想用 Java 实现对象,称为"Family"。在它的构造函数中,我希望这个对象链接到他们的邻居,所以当我创建一个家庭对象时,我需要最大。另外两个家庭对象。

public class Family {

    Family leftNeighbour;
    Family rightNeighbour;

    public Family(Family leftNeighbour, Family rightNeighbour) {
        this.leftNeighbour = leftNeighbour;
        this.rightNeighbour = rightNeighbour;
    }   
}

现在,我开始初始化三个家庭: A是第一个,所以它只有一个右邻居,B有两个,C最后一个,只有一个左邻居。

问题:

Family A = new Family(null,B);
Family B = new Family(A,C);
Family C = new Family(B, null);

我无法初始化 A,因为 B 尚未创建。另外,我无法初始化 B,因为缺少 A。有没有可能在没有getter 和 setter 的情况下解决这个问题(发现它有点难看,以防我需要大量的家庭对象)。

4

3 回答 3

5

您可以将其添加到构造函数中:

if (leftNeighbour != null)
  leftNeighbour.rightNeighbour = this;
if (rightNeighbour != null)
  rightNeighbour.leftNeighbour = this;

然后:

Family A = new Family(null, null);
Family B = new Family(A, null);
Family C = new Family(B, null);

但这很容易出错。

一种更好的方法——“makeNeighbours”方法:

public class Family {
    Family leftNeighbour;
    Family rightNeighbour;

    public Family() {}

    public static makeNeighbours(Family leftNeighbour, Family rightNeighbour)
    {
        leftNeighbour.rightNeighbour = rightNeighbour;
        rightNeighbour.leftNeighbour = leftNeighbour;
    }
}

然后:

Family A = new Family();
Family B = new Family();
Family C = new Family();
Family.makeNeighbours(A, B);
Family.makeNeighbours(B, C);

一个相关的替代方案 -makeNeighbours采用可变数量的参数
(受 Ray Toal 答案的启发):

public static makeNeighbours(Family... families)
{
   for (int i = 1; i < families.length; i++)
   {
      families[i-1].rightNeighbour = families[i];
      families[i].leftNeighbour = families[i-1];
   }
}

然后:

Family A = new Family();
Family B = new Family();
Family C = new Family();
Family.makeNeighbours(A, B, C);
于 2013-06-02T20:09:47.697 回答
1

最好的方法是创建一个名为createSequenceOfFamilies参数化的公共静态方法,用一个整数表示您想要多少个家庭。在该方法中,您可以直接设置leftNeighbourandrightNeighbour字段。

这样你就可以避免设置器并使你的对象不可变。

你的电话会是这样的

Family a = Family.createSequenceOfFamilies(3);

那么你所称的b将是a.getRightNeighbour(),你的c成为b.getRightNeighbour()

于 2013-06-02T20:09:29.047 回答
0

要编译您的代码,您可以执行以下操作:

Family A = null;
Family B = null;
Family C = null;

A = new Family(null, B); 
B = new Family(A, C);
C = new Family(B, null);

但是您仍然需要在某些时候使用 setter 设置值。因为您无法分配尚未创建的对象。如果你想避免设置器,你可以创建另一个包装设置器的方法,但你必须使用它们。

于 2013-06-02T20:04:03.613 回答