iterate through recursive objects

前端 未结 5 1586
孤独总比滥情好
孤独总比滥情好 2021-01-29 14:54

I am trying to iterate through a recursive object but Java has no support for this from what I know.

For example, given the object Item:

pub         


        
5条回答
  •  攒了一身酷
    2021-01-29 15:30

    If you don't have cycles within the parent-child tree you can use a simple recursive function to determine the number of descendants:

    public class Item {
        ...
    
        public int getDescendantCount() {
            int count = 0;
            if (children != null) {
                 count += children.size();
                 for (Item child : children)
                      count += child.getDescendantCount();
            }
            return count;
        }
    }
    

提交回复
热议问题