Java集中的并发修改异常

时间:2014-03-10 18:45:13

标签: java collections concurrentmodification

作为我程序的一部分,我坚持使用Concurrent Modification Exception。这是上面提到的部分:

PriorityQueue<Customer> marginalGainHeap = new PriorityQueue<Customer>(
            1, new Comparator<Customer>() {
                public int compare(Customer c1, Customer c2) {
                    return Double.compare(c1.getMarginalGain(),
                            c2.getMarginalGain());
                }
            });

    // set of all remains available nodes
    availableNodes.removeAll(churnNet);
    for (Customer avail : availableNodes) {
        avail.setMarginalGain(0);
        marginalGainHeap.add(avail);
    }
    while (seedSet.size() <= budget) {
        **for (Customer remainingNode : availableNodes) {**

            remainingNode.setMarginalGain(calculateMarginalGain(
                    remainingNode, seedSet, network, availableNodes,
                    churnNet));

            marginalGainHeap.remove(remainingNode);
            marginalGainHeap.add(remainingNode);
        }
        seedSet.add(marginalGainHeap.poll());
    }

这是calculateMarginalGain方法:

private int calculateMarginalGain(Customer remainingNode,
            HashSet<Customer> seedSet,
            DirectedSparseGraph<Customer, Transaction> net,
            Set<Customer> availableNodes, HashSet<Customer> churnNetwork) {
        // Marginal gain for short-term campaign
        HashSet<Customer> tmp = new HashSet<Customer>(); // seedset U
                                                            // {remainingNode}
        tmp.add(remainingNode);
        Set<Customer> tmpAvailableNodes = availableNodes;
        HashSet<Customer> NeighborOfChurn = getNeighbors(churnNetwork, net);
        // sigma function for calculating the expected number of influenced
        // customers- seedSettmp=seedset U {u}
        tmpAvailableNodes.removeAll(NeighborOfChurn);
        Set<Customer> influencedNet = getNeighbors(tmp, net);
        tmpAvailableNodes.retainAll(influencedNet);
        return tmpAvailableNodes.size();
    }

我在用**指定的程序行中遇到此异常。我发现这个错误可能是由迭代器引起的。但我没有使用任何一个!请帮助我找出导致该异常的原因以及如何解决这个问题?

问候。

2 个答案:

答案 0 :(得分:3)

将您设置转换为数组可能会解决您的问题

示例:

Set<String> set = new Set<String>(size);
String[] array = set.toArray(new String[set.size()]);

所以在你的for循环中你可以做类似的事情:

for(String foo : set.toArray(new String[notis.size()])) {
    // Loop stuff here
}

答案 1 :(得分:1)

**for (Customer avail : availableNodes) {**
    avail.setMarginalGain(0);
    marginalGainHeap.add(avail);
}

这是一个迭代。它被称为“简化循环”。并且在使用这种形式的循环时,您无法修改迭代的元素。相反,使用

for (int i = 0; i < availableNodes.size(); i++) {
 Customer currentNode = availableNodes.get(i);
 currentNode.setMarginalGain(0);
 marginalGainHeap.add(currentNode);
}