0

I'm a Student, so I'm not an expert. I'm trying to do the following:

I have an HashMap with some Keys (String) and Values (String[]). I also have a file.txt with all the synonyms. I was trying to add the synonyms to my HashMaps, and to get the values of the existing Key (synonym of the synonyms).

Here is my HashMap:

HashMap<String, String[]> qA = new HashMap<String, String[]>();

Here is my code:

for (Map.Entry<String, String[]> entry : getqA().entrySet()) {
        for (String synonym : getSynonym(entry.getKey()))
            addWord(synonym.toLowerCase(), entry.getValue());
    }

The method getqA returns the HashMap. The method addWord is practically the same as nameOfTheHashMap.put();

There is the method getSynonym(String word):

public String[] getSynonym(String word) {

    for (String[] list : abc)
        for (String wordIntoList : list)
            if (wordIntoList.toLowerCase().equals(word.toLowerCase().replace(" ", "")))
                return list;

    return new String[] {};
}

"abc" is an ArrayList<String[]> (contains file.txt) which contain on every index a line. A line is formed by sinonyms with the same meaning.

How do I fix the error ConcurrentModificationException? As I said, I'm not an expert, it's the first year I study Java. I've tried to look other topics, but I wasn't able to fix the problem.

Thanks in advance!

As requested, my addWord method:

    public static void addWord(String key, String[] values) {
    qA.put(key, values);
}
Kenny Grant
  • 9,360
  • 2
  • 33
  • 47
OldTester
  • 1
  • 2
  • Post the code for your `addWord` method. Likely, it's modifying the map, which you should probably not do within iteration. – Mena Jul 06 '16 at 12:23
  • That happens because you are modifying the map while you are iterating over it. – Jesper Jul 06 '16 at 12:23
  • Done, method added, @Mena – OldTester Jul 06 '16 at 12:25
  • And, as we can see, it indeed modifies the map by calling `put` on the map. You get a `ConcurrentModificationException` if you call anything in the loop that modifies the map. – Jesper Jul 06 '16 at 12:26
  • @Jesper, what is the alternative to do what I need? I would really appreciate it. – OldTester Jul 06 '16 at 12:27
  • Change your code in such a way that you don't modify the map while you are iterating it. For example, add the words to a new, separate map, and then add everything from that temporary map to the original map after the loop. – Jesper Jul 06 '16 at 12:29
  • @xMarcoGP well, your question was rightfully marked as duplicate. Take a look at the linked question. – Mena Jul 06 '16 at 12:29
  • Problem solved, thank you very much! – OldTester Jul 06 '16 at 12:40

0 Answers0