recursion - Recursive object setting java -


i have model call section. section has 2 fields: color , list of section objects.

public class section{     public string color;     public list<section> sub_sections;   } 

suppose json feed list of section objects. within each section object color field set random color , list of section objects. within these nested section lists color fields set empty string. dont know how many nested sections there are.

how set nested color strings within nested sections same color first level section? code below non recursive 3 levels deep give ides of problem.

for(section section : sectionslist){         for(section sub : section.sub_sections){             sub.color=section.color;             if(sub.sub_sections.size()> 0){                 for(section sub2 : sub.sub_sections){                     sub2.color=sub.color;                     if(sub2.sub_sections.size()> 0){                         for(section sub3 : sub2.sub_sections){                             sub3.color=sub2.color;                         }                     }                 }             }         }     }  

if understand you, may solution. need public starting method without parameters , recursive method gets original color set.

public class section{   public string color;   public list<section> sub_sections;    /** propagates current section color sub sections. */   public void propagate() {     propagate(this.color);   }    /** propagates passed color section , sub sections recursively. */   private void propagate(string propagatedcolor) {     color = propagatedcolor;     (section sub : sub_sections) {       sub.propagate(propagatedcolor);     }   }  } 

than usage code like:

for (section section : sectionslist) {   section.propagate(); } 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -