MemoryObjectTreeNode implements MutableTreeNode { @NotNull public List<MemoryObjectTreeNode<T>> getPathToRoot() { List<MemoryObjectTreeNode<T>> path = new ArrayList<>(); MemoryObjectTreeNode<T> currentNode = this; MemoryObjectTreeNode<T> cycleDetector = this; while (currentNode != null) { for (int i = 0; i < 2 && cycleDetector != null; i++) { assert cycleDetector.myParent != currentNode; cycleDetector = cycleDetector.myParent; } path.add(currentNode); currentNode = currentNode.myParent; } Collections.reverse(path); return path; } MemoryObjectTreeNode(@NotNull T adapter); @Override TreeNode getChildAt(int i); @Override int getChildCount(); @Override TreeNode getParent(); @Override int getIndex(TreeNode treeNode); @Override boolean isLeaf(); @Override Enumeration children(); @NotNull ImmutableList<MemoryObjectTreeNode<T>> getChildren(); @Override boolean getAllowsChildren(); void add(@NotNull MemoryObjectTreeNode child); @Override void insert(MutableTreeNode newChild, int childIndex); @Override void setParent(@Nullable MutableTreeNode newParent); @Override void remove(int childIndex); @Override void remove(MutableTreeNode node); @Override void removeFromParent(); void removeAll(); @Override void setUserObject(Object object); @NotNull T getAdapter(); void sort(@NotNull Comparator<MemoryObjectTreeNode<T>> comparator); @Nullable Comparator<MemoryObjectTreeNode<T>> getComparator(); @NotNull List<MemoryObjectTreeNode<T>> getPathToRoot(); void select();  }
@Test(expected = AssertionError.class) public void testGetPathToRootSelfCycleDetection() { MemoryObjectTreeNode<TestMemoryObject> selfCycle = new MemoryObjectTreeNode<>(new TestMemoryObject()); selfCycle.myParent = selfCycle; selfCycle.getPathToRoot(); }
@Test(expected = AssertionError.class) public void testGetPathToRootCycleDetection() { MemoryObjectTreeNode<TestMemoryObject> node1 = new MemoryObjectTreeNode<>(new TestMemoryObject()); MemoryObjectTreeNode<TestMemoryObject> node2 = new MemoryObjectTreeNode<>(new TestMemoryObject()); MemoryObjectTreeNode<TestMemoryObject> node3 = new MemoryObjectTreeNode<>(new TestMemoryObject()); node1.myParent = node2; node2.myParent = node3; node3.myParent = node1; node1.getPathToRoot(); }