0

I've been having problems with a database functional dependency algorithm I have been developing. I am trying to calculate functional dependencies given the current level of the lattice and the list of column heads (not really relevant).

I am trying to iterate through a list of string headers, as well as looping through the characters of each string. Reasoning with this, I then use these values to remove a string from a List<String> value in a map. The Map has structure <String, List<String>> and I want to simply remove a value from the List<String> values of the HashMap. colHeads is a List<String>.

I am getting ConcurrentModificationException when I start to loop through the list:

for (String x: level) {
        for (char a : x.toCharArray()) {
            if (cPlusHash.get(x).contains(Character.toString(a))) {
                if (checkFD(Arrays.asList(x.replace("a", "")), Arrays.asList(Character.toString(a)))){
                    fds.add(x.replace("a", "") +", "+ a );  
                    cPlusHash.remove(x, Character.toString(a));



                    for (char j : x.toCharArray()) {
                        if (colHeads.contains(Character.toString(j))) {
                            colHeads.remove(Character.toString(j));
                        }
                    }
                    for (String b : colHeads) {
                        if (cPlusHash.get(x).contains(b)) {
                            cPlusHash.remove(x, b);
                        }
                    }
                }
            }
        }

I am getting the error thrown on the first line of this snippet of code. I am confused as I'm not actually trying to modify the value of the List I'm iterating through.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

0

You can't modify a List or Map while you are looping through it in most cases. The solution is to obtain an Iterator, which provides the remove() method. This allows the Iterator to be aware of changes and to not "lose it place."

Steve11235
  • 2,849
  • 1
  • 17
  • 18
0

You are trying to modify the map cPlusHash <String, List<String>> while you are reading which is not allowed and leads to ConcurrentModificationException.

https://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html

For your case is a single thread case:

If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.

hoan
  • 1,058
  • 8
  • 13