![](/img/trans.png)
[英]java: how do I stop people from clearing my arraylist<string> When I use a getter method?
[英]2 Questions: ArrayList alternative? And how do I stop my Thread from freezing when my mouse exits?
1)所以我有一个游戏,大炮发射子弹,它在数组列表中添加了 Bullet.class,但每次我在该数组列表中添加或删除一个对象时,它都会滞后于游戏/线程。 除了 Bullet[] 数组之外,还有其他 ArrayList 替代品吗?
已解决:这是我的显卡。 哈哈。
2) 我在我的游戏中也使用鼠标,但是当鼠标离开游戏窗口时游戏会冻结。 我认为这是因为它在同一个线程中运行,但我仍然不太确定。 我怎样才能停止这个问题?
子弹类:
import java.awt.Rectangle;
import java.util.ArrayList;
public class Bullet {
public static ArrayList<Bullet> bullets = new ArrayList<Bullet>();
private int id;
private double velX, velY, x, y;
private double r;
private boolean isAlive;
public int getId(){return id;}
public double getX(){return x;}
public double getY(){return y;}
public double getVelX(){return velX;}
public double getVelY(){return velY;}
public double getRotation(){return r;}
public boolean isAlive(){return isAlive;}
public Rectangle getBounds(){Rectangle r = new Rectangle((int)x-32, (int)y-12, 32, 32); return r;}
public void setX(double x){this.x = x;}
public void setY(double y){this.y = y;}
public void setVelX(double x){this.velX = x;}
public void setVelY(double y){this.velY = y;}
public void remove(){this.isAlive = false;}
public Bullet(int x, int y, double r, double velX, double velY){
this.x = x;
this.y = y;
this.velX = velX;
this.velY = velY;
this.r = r;
this.isAlive = true;
bullets.add(this);
}
}
当然,ArrayList 有替代方案,例如 LinkedList 或其他一些实现。 但是这两种方法都不会很慢,尤其是当您一次只添加单个对象时。 我要说的是,延迟的来源可能不是将Bullet
实例添加到列表中。
那个时候你还有其他的事情吗? 你的列表同步了吗? 还有别的锁吗? 您的项目符号是否包含每次创建Bullet
实例时可能从您的磁盘加载的图像文件? (磁盘I/O速度慢,播放时不要加载东西)
" but every single time I add or delete an object in that arraylist it laggs the game/thread."
:我敢打赌,您遇到了XY 问题,因为您的问题可能与 ArrayList 运行缓慢或导致延迟无关,而一切都与您的代码有问题有关,因为您存在一个未识别的错误将需要找到。问题 1 只是我的廉价图形芯片。 解决这个问题的一种方法。
问题#2 当鼠标离开屏幕时游戏冻结。 我添加到我的主类: this.addMouseMotionListener(i); 这解决了它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.