Help with java hash map

can someone explain what happens in the code below and how does it end with 36?

thank

edit 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);
        }
    }
}
+3
source share
4 answers

This is a simple recursion example , which leads to summing all the keys on the card one at a time and when the card is empty, it adds 11 more. This sums up to 36.

+5
source

To make the recursive function , each time it is called, add the value of the first element on the map and then delete it.

If the card is empty, it returns 11

: 9+7+5+3+1+11 = 36 (9,7,5,3,1 11, )

, ( )

( , ) :

import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
public class ArrayList2009 {
    public static void main( String [] args ) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(3);
        list.add(5);
        list.add(7);
        list.add(9);
        System.out.println( addOne( list ) );                        
    }
    private static int addOne( List<Integer> list ){
        if ( list.isEmpty() ) {
            return 11;
        } else {
            Iterator<Integer> i = list.iterator();
            int num = i.next();
            i.remove();
            return num + addOne( list );
        }
    }
}

, , List .

+2

oddOne

  • oddOne ( )

whne oddOne return 11

1 + (3 + (5 + (7 + (9 + 11)))) = 36

, -,

0

, .

You can start with num == 1 (map is unordered) and you will remove this from your map. Then you make a recursive call that gives you num == 3. This continues until your card is empty, which leads to 1 + 3 + 5 + 7 + 9 and 11 more for your empty card.

Take a look at recursion: http://en.wikipedia.org/wiki/Recursion

0
source

Source: https://habr.com/ru/post/1748434/


All Articles