Search code examples
javaloopshashmapinstanceput

Using Map.put(String, Integer) in a loop


I´ve got a short question. I am so despaired because of my problem. I just want to put different Keys with the same Value in my Map by using a loop. My main executes the function einfuegen() for multiple times. As in the following code block:

Woerterbuch woerterbuch2 = new Woerterbuch2();
for (Medium m : medienliste) {
    for (String s : m.getWorte()) {
        woerterbuch2.einfuegen(s);
    }
}

By the way I have tested all the loops and assignments of the variables.

Now einfuegen() should put all the the Strings s in the Map. See the following code block:

public class Woerterbuch2 implements Woerterbuch{

    HashMap<String, Integer> liste = new HashMap<>();

    public void einfuegen(String word) {
        // I have deleted all the previous unimportant code
        liste.put(word, 1);
    }
}

My map only contains one entry, although the function einfuegen() is running for more than one time and there are more than one different String that is assigned to word. Normally my map should contain more than 50 different words, because einfuegen() is executed for more than 50 times.

My assumption is that Java overwrites the connection from 1 to word because 1 is always the same instance of Integer. If I´m right I still don´t know how to fix it.

Thanks for your help. I am really looking forward to it =)


Solution

  • It doesn't matter if you have contant value for all your keys. But it matters if you are giving constant key.In case all the keys are same a single entry will be made .Debug your code to make sure that the Keys are unique.

    1) Print the values in m.getWorte() to check that all keys sent are unique.

    Have a look at Example Code

    HashMap<String, Integer> myMap = new HashMap<>();
            myMap.put("s", 1);
            myMap.put("r", 1);
            myMap.put("m", 1);
            System.out.println(myMap); // This prints {r=1, s=1, m=1}
    
    HashMap<String, Integer> myMap1 = new HashMap<>();
        myMap1.put("s", 1);
        myMap1.put("s", 2);
        myMap1.put("s", 3);
        System.out.println(myMap1); // This prints {s=3}
    

    i.e entries are made in hashmap irrespective of values being constant and entries are ignored in hashmap if keys are same irrespective of different values