can some one please explain what is happening in the code below and how it ends up with 36?
thanks
edit by Amir Rachum
public class HashMap2009 {
public static void main (String[] args) {
Map<String, Integer> myMap2009 =
new HashMap<String, Integer>();
myMap2009.put("one", new Integer(1));
myMap2009.put("three", new Integer(3));
myMap2009.put("five", new Integer(5));
myMap2009.put("seven", new Integer(7));
myMap2009.put("nine", new Integer(9));
System.out.println(oddOne(myMap2009));
}
private static int oddOne(Map<String, Integer> myMap2009) {
if (myMap2009.isEmpty())
return 11;
else {
Set<String> st = myMap2009.keySet();
String key = st.iterator().next();
int num = myMap2009.get(key);
myMap2009.remove(key);
return num + oddOne(myMap2009);
}
}
}
This is a simple example of recursion, which results in adding up all the keys in the map one by one and when the map is empty, it adds another 11. This sums up to 36.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With