You can set parent to private and change the parent value using the setParent(Company) method. Then:
public boolean setParent(Company parent) { Company curr = parent; while (curr != null) { if (curr.equals(this)) { return false; // Failed as cycle } else { curr = curr.getParent(); } } this.parent = parent; return true; }
As a rule, bad practice has public variables, since it interrupts encapsulation.
If you cannot change the field to private , then:
public List<Company> hasCycle(List<Company> companies) { while (companies.size() > 0) { List<Company> cycle = new ArrayList<Company>(); Company curr = companies.get(companies.length() - 1); cycle.add(curr); while (curr.parent != null) { curr = curr.parent; if (cycle.contains(curr)) { return cycle;
Edit: The hasCycle return has been hasCycle to return a List<Company> containing all the companies in the loop for further processing (print them, delete, etc.).
source share