A cycle occurs when traversal returns to an element already visited. In recursive code, revisiting the same state can consume stack space indefinitely and end in StackOverflowError. section 5.4.2
Handle cycles according to whether they are valid or symptoms of another defect:
- When cycles are legal, record previously visited nodes and skip repeated visits. section 5.4.2 section 5.5
- When a tree-like structure should be acyclic, fix the earlier mistake instead of weakening a correct traversal. section 5.4.2
- Avoid adding collections to themselves; hashCode() cannot calculate such a list by specification, while toString() protection covers only direct self-cycles. section 5.4.2
A self-referential list
A list that contains itself creates a cycle. Calling hashCode() on it throws StackOverflowError; a longer indirect cycle can also defeat the limited protection in toString().




