Java 集已满 [英] Java Set gets full

查看:35
本文介绍了Java 集已满的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作粒子发射器.每个渲染"对象都存储在一个 HashSet 中,当屏幕上有很多粒子时,控制台会吐出并发修改异常.我通常对这些粒子的生命周期很短,所以它们会在几秒钟后被删除,但我相信这在未来可能会成为一个问题.我该如何解决这个问题?

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?

代码:

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;
}
}

推荐答案

ConcurrentModificationException 意味着您在迭代时修改了集合.这并不意味着集合已满.

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

例如,以下代码将抛出 ConcurrentModificationException:

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");

请注意,不能保证您会收到 ConcurrentModificationException,因此您应该避免捕获它.您应该改为修复您的代码,以免它导致问题.

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.

这篇关于Java 集已满的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆