6

I am trying to create a huffman tree, and am in the middle of attempting to merge two trees. I can not figure out how to remove a Tree in my program without getting the "concurrent Modification Exception" because I am iterating over a list and attempting to remove from the list at the same time.

BinaryTree<Character, Integer> t1 = null;
        BinaryTree<Character, Integer> t2 = null;
        BinaryTree<Character, Integer> tFinal = null;
        int treeSize = TREES.size();

        for (int i = 0; i < treeSize; i++) {

            for (BinaryTree<Character, Integer> t : TREES) {
                System.out.println("treeSize " + treeSize);
                System.out.println(t.getRoot().getElement()
                        + "  t.getRoot().getElement()");

                // here I edited the merge function in Binary Tree to set
                // the new root
                // to have null value for value, and itemTwo for weight
                System.out.println(t.getRoot().getValue() + " weight of tree \n");
                t1 = t;
                TREES.remove(t);

            }
            for (BinaryTree<Character, Integer> t : TREES){
                t2 = t;
                System.out.println(t);
            }
            int weight = t1.getRoot().getElement() + t2.getRoot().getElement();
            tFinal.merge(null, weight, t1, t2);
        }
shrimpah
  • 125
  • 1
  • 2
  • 7

4 Answers4

8

Java prevents you from modifying collections in a loop. You will need to use an iterator.

Captain Skyhawk
  • 3,499
  • 2
  • 25
  • 39
4

If you want to modify the list while iterating over it, you need to use Iterator.

Below are some SO questions answering this:

Community
  • 1
  • 1
Apurv
  • 3,723
  • 3
  • 30
  • 51
3

Your code doesn't compile, so we're limited in the way we can help you. But in general, the way you resolve this issue is to use an Iterator instead of a foreach loop.

For example, this gives a concurrent modification exception:

    List<String> l = new ArrayList<String>(asList("a", "b", "c"));
    for (String s : l) {
        l.remove(s);
    }

But this doesn't, and it gives you the result you'd want:

    List<String> l = new ArrayList<String>(asList("a", "b", "c"));
    for (Iterator<String> iterator = l.iterator(); iterator.hasNext(); ) {
        String s = iterator.next();
        iterator.remove();
    }
    System.out.println(l.size());

The latter will output "0".

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
1

A solution is to store in another list the items you want to remove, and then, after iterating, remove them.

Thierry
  • 5,133
  • 3
  • 25
  • 30