0

I have a simple Immutable Linked list class the following:

class Node<T> {
    final T val;
    final Node next;
    Node(T val, Node next) {
        this.val = val;
        this.next = next;
    }
}

I would like to create an instance which has itself as the next node, thereby creating a circular list.

I obviously can't do Node x = new Node<>(0, x), since x won't be defined by the time it should be passed to the constructor.

Are there any tricks that'd allow me to create this without changing Node?

For example, http://stackoverflow.com/a/25473855/205521 describes how to do something similar for lambda functions, that is a function which refers to itself (recursion). I, however, wasn't able to make it work for initialization.

Thomas Ahle
  • 30,774
  • 21
  • 92
  • 114
  • 1
    No. Since the field is final, not even reflection can change the field's value. – f1sh Sep 17 '19 at 08:08
  • you can have a setter for the next Node and set it after instantiation. (But that will not work if you keep it `final`), or you set it in your constructor. So in your constructor you say `this.next = this`; – divjo Sep 17 '19 at 08:14
  • Depends on how tricky you want to go. I mean `Unsafe` exists, but IMO that actually goes outside of the scope of "possible in Java". – Joachim Sauer Sep 17 '19 at 08:15
  • 2
    @f1sh don't you mean "you'd have to use reflection to change the field's value"? A simple `final` is no match for `.setAccessible(true)`. – Kayaman Sep 17 '19 at 08:18
  • @Kayaman I didn't know that. I thought `final` was a runtime thing too! – f1sh Sep 17 '19 at 08:21
  • @f1sh I wasn't thinking of reflection, but of tricks similar to how you do recursive lambda functions: https://stackoverflow.com/a/25473855/205521 – Thomas Ahle Sep 17 '19 at 12:05
  • Why do you want to use complicated tricks, instead of just making the trivial change to the `Node` class? – Holger Sep 18 '19 at 14:31
  • 1
    @f1sh `final` is a runtime thing, but more complicated. Ordinary bytecode still may not write to a `final` field outside a constructor and `static final` fields are not allowed to be changed even via Reflection (letting off-specification hacks aside). The reflective modification of `final` instance field is allowed explicitly, to aid cloning and serialization code. – Holger Sep 18 '19 at 14:45
  • @Holger What change are you suggesting? Making the class not immutable? There is a host of reasons to who I prefer immutable classes. – Thomas Ahle Sep 18 '19 at 17:46
  • 1
    Adding another special constructor that can assign `this` to `next`. Or to allow circles of arbitrary length: https://stackoverflow.com/a/57995933/2711488 – Holger Sep 18 '19 at 17:50

0 Answers0