简体   繁体   中英

recursive method

I want to retreive at the finaly of call recursive method, a set of integer with result : {10,20,30} but in this program i have porblem ,

  public static void main(String[] args) {
     HashMap<Integer, Set<Integer>> myMap = new HashMap();
     myMap.put(1, new HashSet(){{add(10);}});
     myMap.put(2, new HashSet(){{add(20);}});myMap.get(2).add(30);
     myMap.put(3, new HashSet());

     HashSet<Integer> setInteg = new HashSet();
     recursivFonc(setInteg, myMap, 1);
     System.out.println(setInteg);
}

static HashSet recursivFonc(HashSet<Integer> setInteg, HashMap<Integer, Set<Integer>> map, int cont)
{
    System.out.println(cont);
    if(map.get(cont) != null)
    {
        Set<Integer> set = map.get(cont);
        for(Integer intg : set)
        {

            setInteg.add(intg);
            return recursivFonc(setInteg, map, cont);
        }
    }
    return setInteg;
}

how did I do to get to the end a set with {10,20,30} ?

You have a return statement inside the for loop. Because of this, the for loop iterates only once. Instead, move the return statement outside of the for-loop. Therefore; the loop will iterate over all elements of the set.

You might also want to increment cont at each recursive call. Because the exit point for the recursive calls depends on whether map.get(cont) is null or not. If you never change the value of cont , it is 1 initially. Each call to the method will be passed 1 and it will go on for a long time (until you are out of memory, I guess).

static HashSet recursivFonc(HashSet<Integer> setInteg, HashMap<Integer, Set<Integer>> map, int cont)
    {
        System.out.println(cont);
        if(map.get(cont) != null)
        {
            Set<Integer> set = map.get(cont);
            for(Integer intg : set)
            {

                setInteg.add(intg);
            }
            return recursivFonc(setInteg, map, cont + 1);
        }
        return setInteg;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM