Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The answer of the linked question is easily expandable to an arbitrary number of objects, if you have a way to specify the needed nodes at construction time, e.g.

final class CircularLinkedList<T> {
    final CircularLinkedList<T> next;
    final T value;

    public CircularLinkedList(T firstValue, List<T> other) {
        value = firstValue;
        next = other.isEmpty()? this: new CircularLinkedList<>(this, 0, other);

    }
    private CircularLinkedList(CircularLinkedList<T> head, int pos, List<T> values) {
        value = values.get(pos);
        next = ++pos == values.size()? head: new CircularLinkedList<>(head, pos, values);
    }

    @Override
    public String toString() {
        StringJoiner sj = new StringJoiner(", ").add(value.toString());
        for(CircularLinkedList<T> node = next; node != this; node = node.next)
            sj.add(node.value.toString());
        return sj.toString();
    }
}

Which you can use like

CircularLinkedList<String> cll
    = new CircularLinkedList<>("first", Arrays.asList("second", "third", "fourth"));
System.out.println(cll);

// demonstrate the wrap-around:
for(int i = 0; i < 10; i++, cll = cll.next) {
    System.out.print(cll.value+" .. ");
}
System.out.println(cll.value);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...