Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete from a list, while modifying the list [duplicate]

Tags:

java

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);
        }
like image 367
shrimpah Avatar asked Apr 28 '13 19:04

shrimpah


People also ask

Does converting set to list remove duplicates?

When you convert a list into a set, all the duplicates will be removed. The set can then be converted back into a list with list() . The drawback of this method is that the use of set() also changes the original list order, which is not restored after it is converted back into a list.

How do you remove duplicates from a list whilst preserving order?

If you want to preserve the order while you remove duplicate elements from List in Python, you can use the OrderedDict class from the collections module. More specifically, we can use OrderedDict. fromkeys(list) to obtain a dictionary having duplicate elements removed, while still maintaining order.


1 Answers

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

like image 185
Captain Skyhawk Avatar answered Sep 18 '22 22:09

Captain Skyhawk