这个问题是 this question 的延伸.
我有一个类似于以下的类(class)。
class HighlightableStructure {
private final HighlightableStructure NEXT;
HighlightableStructure(HighlightableStructure next) {
NEXT = next;
}
}
其中 HighlightableStructure
指向下一个要突出显示的结构。
有时,这些 HighlightableStructure
会循环并引用之前的 HighlightableStructure
,但不是链中的第一个。类似于 h_1 -> h_2 ->h_3 -> ... -> h_n -> h_2,其中 h_i 是 HighlightableStructure
的实例。
我是否可以在不反射或失去不变性的情况下构造这样的东西?
最佳答案
answer of the linked question如果您有办法在构造时指定所需的节点,则可以轻松扩展到任意数量的对象,例如
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();
}
}
你可以这样使用
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);
关于java - 有什么好方法可以让不可变对象(immutable对象)链循环起来吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57969903/