Search code examples
javaimmutabilityfinal

Any nice way to make a chain of immutable objects loop around?


This question is an extension of this question.

I have a class similar to the following.

 class HighlightableStructure {
      private final HighlightableStructure NEXT;  

      HighlightableStructure(HighlightableStructure next) {
           NEXT = next;
      }    
 }

where a HighlightableStructure points to the next structure to highlight.

Sometimes, these HighlightableStructures loop around and refer to a previous HighlightableStructure, but not the first in the chain. Something like h_1 -> h_2 ->h_3 -> ... -> h_n -> h_2, where h_i is an instance of HighlightableStructure.

Is there anyway I could construct something like this without reflection or losing immutability?


Solution

  • One possible solution:

    class HSequenceBuilder {
        private long id = 0;
        private final Map<Integer, H> map = new HashMap<Integer, H>();
    
        static H create(int next) {
            H h = new H(id, next, Collections.unmodifiableMap(map));
            map.put(id, h);
            id++;
            return h;
        }
    
        static H create() {
            create(id + 1);
        }
    
    }
    
    class H {
        private final id;
        private final Map<Integer, H> map;
        private final int next;
    
        H(int id, int next, Map<Integer, H> map) {
            this.id = id;
            this.next = next;
            this.map = map;
        }
    
        int getId() { return id; }
    }
    HSequenceBuilder builer = new HSequenceBuilder();
    H h1 = builder.create(); // 1.
    H h2 = builder.create(); // 2.
    H h3 = builder.create(h2.getId()); // 3.