I am doing a program to compress a file (which is represented as an ArrayList of Byte ) and at some point I have to replace all occurrences of a pre-defined "string" by a single byte("string" as a sequence of bytes, not a String in the Java language).
The "pre-defined string" of type ArrayList of Byte is stored in the variable opt_word, and its length is stored in the variable opt_length, and is always >=2
I am getting a Concurrent Modifiation exception at the place noted "HERE". Further debugging showed me that the exception happens on the loop iteration right after the first replacement.
I know other people asked about similar issues like here and here, but my case is quite different from theirs. I use a standard for loop.
CopyOnWriteArrayList<Integer> removal_indexes = new CopyOnWriteArrayList<Integer>();
for(int j=0, l=0; j <= encoded.get(k).size() - opt_length; ++j, ++l)
{
List<Byte> str = encoded.get(k).subList(j, j + opt_length);
if (str.equals(opt_word)) // <-- here
{
removal_indexes.add(l);
j += opt_length - 1;
}
}
for(int l=0; l < removal_indexes.size(); ++l)
{
encoded.get(k).set(removal_indexes.get(l), (byte)(lowr + lengths.size()));
for(int i=1; i < opt_length; ++i)
encoded.get(k).remove(removal_indexes.get(l)+1);
}