Search code examples
javaconstructorfinal

Two objects refer to each other with final references


I have a class that looks something like this:

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

and want to do something like

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

but obviously cannot since n2 is not initialized yet. I don't want to use a setter to set otherNode because it's final, and thus should only be set once ever. What is the cleanest approach to accomplishing this? Is there some fancy Java syntax I'm unfamiliar with to let me do this? Should I use an initialize method in addition to the constructor (ugly), or just cave and use a setter (also ugly)?


Solution

  • Have a second constructor that takes no parameters and constructs its own Node, passing itself as the other's "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;
       }
    }
    

    Then when using it:

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

    Assuring that they refer to each other:

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

    These all print true.