Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

Java Set gets full

I am making a particle emitter. Every "Rendered" object is stored in a HashSet, and when there's lots of particles on the screen, the console spits out concurrent modification exceptions. I usually have a short lifetime on these particles so they get deleted after several seconds, but I am sure this could potentially be a problem in the future. How can I fix this?

EDIT: Code:

public class UpdatedManager {
private static Set<Updated> updates = new HashSet<>();

private UpdatedManager() {}

public static Set<Updated> getUpdates() {
    return new HashSet<Updated>(updates);
}
public static boolean registerUpdated(Updated u) {
    return updates.add(u);
}
public static boolean unregisterUpdated(Updated u) {
    return updates.remove(u);
}
public static void update() {
    for (Updated up : new HashSet<Updated>(updates))
        up.update();
}
public static Set<GameObject> getGameObjects() {
    Set<GameObject> objs = new HashSet<>();
    for (Updated up : new HashSet<Updated>(updates)) {
        if (up instanceof GameObject)
            objs.add((GameObject) up);
    }
    return objs;
}
public static Set<GameObject> getGameObjectsByName(String name) {
    Set<GameObject> objs = new HashSet<>();
    for (GameObject go : new HashSet<GameObject>(getGameObjects())) {
        if (go.getName() != null && go.getName().equals(name))
            objs.add(go);
    }
    return objs;
}
public static Set<Particle> getParticles() {
    Set<Particle> parts = new HashSet<>();
    for (Updated up : new HashSet<Updated>(updates)) {
        if (up instanceof Particle)
            parts.add((Particle) up);
    }
    return parts;
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A ConcurrentModificationException means you modified the set while iterating over it. It does not mean the set is full.

For example, the following code will throw a ConcurrentModificationException:

Set<String> set = new HashSet<>();

set.add("Hello");

for(String s : set)
    set.add(s+" world");

Note that you are not guaranteed to get a ConcurrentModificationException, so you should avoid catching it. You should instead fix your code so that it doesn't cause the problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...