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

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -