0

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} ?

1 Answer 1

4

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; } 
Sign up to request clarification or add additional context in comments.

4 Comments

Actually, it's going to crash very fast due to a StackOverflowError.
Oups yes of corse ! but why result is [10, 20] and not [10, 20, 30] ? return recursivFonc(setInteg, map, cont+1);
@user1149157 - The result should be [20, 10, 30] as expected? Have you tried incrementing cont and moving the return statement outside the loop.
when i execute this programe, set result is [10, 20] and normally it is [10, 20, 30]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.