jumps4fun
jumps4fun

Reputation: 4130

How can i pinpoint a circular object reference in a large collection of objects?

I am retrieving, and copying a quite large collection of folder objects from an external source. They all have a folder id, and a parent folder id, but does not come as a tree structure. after retrieving them, I organize them in tree node objects, with a top root. However, one or more of the folders creates a circular reference, and I am having trouble figuring out how to pinpoint where.

Java does not throw any errors when creating the circular reference. The error comes as a stackoverflow error, when I try to encode it to json format, before sending it to the client side of a web application. Because the error is first visible to me then, I can't see which object is the cause of the error at all.

In this particular problem, I am at a loss of a strategy. Are there any standardized, or good ways of recognizing circular object references, like the one in my case?

Upvotes: 2

Views: 80

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

Add a "visited" boolean flag to the node class, initialized to false. Traverse the tree. If at a given node the flag is true when you arrive then you have detected a loop. Otherwise set the flag to true and continue traversing the tree. Makes no differernce which traversal order you use (pre= post- or in-order).

Upvotes: 3

Related Questions