liveBook · Manning

Cycle

As explained in 100 Java Mistakes and How to Avoid Them

A cycle is a path in a graph or linked data structure that eventually returns to an element already visited.

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().

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains repeated state, stack growth, StackOverflowError, visited-node tracking, and self-referential collection behavior.
Examples
Uses self-referential lists, indirect collection cycles, recursive tree traversal, and finite-versus-infinite recursion diagrams.
What it assumes
Assumes recursive traversal and Java collection knowledge while distinguishing legal cycles from accidental structural errors.
What you can do after
Diagnose infinite recursion by checking for cycles, track visited elements when cycles are legal, or repair unintended structure mutations.
How it connects
Connects cycles with infinite recursion, recursive traversal, stack overflow, collections, hashCode(), and toString().

Also explained in

Compare how 5 books explain cycle →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.