簡體   English   中英

兩個對象相互引用,帶有最終引用

[英]Two objects refer to each other with final references

我有一個看起來像這樣的類:

public class Node {
    private final Node otherNode;
    public Node(Node otherNode) {
        this.otherNode = otherNode;
    }
}

並希望做類似的事情

Node n1, n2 ;
n1 = new Node(n2);
n2 = new Node(n1);

但顯然不能,因為n2尚未初始化。 我不想使用setter來設置otherNode,因為它是最終的,因此只能設置一次。 實現這一目標的最簡潔方法是什么? 是否有一些我不熟悉的Java語法讓我這樣做? 我應該使用除了構造函數之外的初始化方法(丑陋),還是只使用一個setter(也很難看)?

有一個第二個構造函數,它不帶參數並構造自己的Node ,將自己作為另一個的“other”傳遞。

public class Node
{
   private final Node otherNode;

   public Node(Node other)
   {
      otherNode = other;
   }

   public Node()
   {
      otherNode = new Node(this);
   }

   public Node getOther()
   {
      return otherNode;
   }
}

然后在使用它時:

Node n1 = new Node();
Node n2 = n1.getOther();

確保他們互相引用:

System.out.println(n1 == n1.getOther().getOther());
System.out.println(n2 == n2.getOther().getOther());
System.out.println(n1 == n2.getOther());
System.out.println(n2 == n1.getOther());

這些都是true

(這是rgettman答案的補充。)

更通用的解決方案是編寫一個構造函數,如:

private Node(final int numNodesInLoop) {
    if(numNodesInLoop < 1) {
        throw new IllegalArgumentException();
    }
    Node head = this;
    for(int i = 1; i < numNodesInLoop) {
        head = new Node(head);
    }
    this.otherNode = head;
}

具有兩個節點的情況將被實例化為new Node(2)

我根據user949300對rgettman的回答進行了上述private ,因為接受intNode構造函數的含義不太可猜測(它創建了一個循環?!),所以最好將它包裝在static工廠方法中其名稱使其功能清晰:

public static Node newNodeLoop(final int numNodes) {
    return new Node(numNodes);
}

(如果您以后需要另外一個構造函數,無論出於什么原因需要使用int ,這也更具有前瞻性。您可以修改此構造函數以獲取偽參數,這足以告訴編譯器構造函數你想要的。工廠方法仍然有相同的合同。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM