迭代hashset并从中删除元素

时间:2017-07-10 00:49:33

标签: java collections iterator

我在代码中进行了while(whiteSet.size()>0)检查,在while块中我调用了dfs方法。该方法修改HashSet。为什么while循环永远不会出错?

public class CycleInDG {
    Set<Vertex> whiteSet = new HashSet<>();
    Set<Vertex> greySet = new HashSet<>();
    Set<Vertex> blackSet = new HashSet<>();
    List<Integer> cyclePath = new ArrayList<>();
    Map<Vertex, Vertex> parentMap = new HashMap<>();
    Graph g = new Graph();

public boolean hasCycle() {
    Map<Integer, Vertex> map = g.getGraphMap();
    Collection<Vertex> vertices = map.values();
    for (Vertex vertex : vertices) {
        whiteSet.add(vertex);
    }
    while(whiteSet.size()>0) {
        parentMap.clear();
        if(dfs(whiteSet.iterator().next(), null)) {
            return true;
        }
    }
    return false;
}
public boolean dfs(Vertex current, Vertex parent) {
    moveVertex(current, whiteSet, greySet);
    for (Vertex vertex : current.getNeighbors()) {
        if(blackSet.contains(vertex)) {
            continue;
        }
        if(greySet.contains(vertex)) {
            parentMap.put(vertex, current);
            return true;
        }
        parentMap.put(vertex, current);
        boolean result = dfs(vertex, current);
        if(result) {
            return result;
        }
    }
    moveVertex(current, greySet, blackSet);
    return false;
}

public void moveVertex(Vertex v, Set<Vertex> src, Set<Vertex> dest) {
    src.remove(v);
    dest.add(v);
}
}

0 个答案:

没有答案