我有一个数组列表,应该向它添加一个对象,但是我第一次尝试向ArrayList添加一个对象时,不添加该对象。ArrayList并不总是添加对象的第一次尝试
主类:
public void keyPressed(KeyEvent e){
char letter = e.getKeyChar();
if(player!=null){
if(letter==' ') {
player.dropBomb(bomb);
}
}
}
Player类:
private int x,y;
private int score;
private Rectangle rect;
private Color color;
private Upgrade upgrades;
private BufferedImage image;
private int bombCount, bombMax;
private int bombs;
private ArrayList<Bomb> bombList;
private ArrayList<Explosion> explodeList;
private int power;
private boolean dead;
private int lives;
public Player(int X, int Y,BufferedImage img) {
x=X;
y=Y;
rect=new Rectangle(x+4,y+3,32-4-5,29-3-4);
bombCount=0;
bombMax=6;
bombList=new ArrayList<Bomb>();
explodeList=new ArrayList<Explosion>();
power=1;
image=img;
dead=false;
lives=3;
}
public void dropBomb(BufferedImage bomb){
out.println("DROPPING "+bombCount);//bombCount is initialized as 0; bombMax is intialized as 6
if(bombCount<bombMax){
bombCount++;
out.println(bombCount+ " "+bombList.size());//bombList is an Arraylist<Bomb>
bombList.add(new Bomb(x+16,y+16));
out.println(bombList);
}
out.println("DROPPINGTest "+bombCount);
}
只有一个球员。
炸弹类的构造函数:
private int power;
private int timeLeft;
private int x,y;
private Rectangle rect;
private boolean canWalk;
public Bomb(int X,int Y){
x=X;
y=Y;
rect=new Rectangle(x,y,32,32);
timeLeft=200;
power=4;
canWalk=true;
}
首次dropBomb被称为:
DROPPING0
1 0
[]
DROPPINGTest 1
第二次dropBomb被称为:
DROPPING1
2 0
[[email protected]]
DROPPINGTest 2
,我运行的唯一线程处于主类。 我正在使用主类中的线程,我试图降低并提高线程上的睡眠时间,结果并没有改变。关于这种情况发生的原因的任何线索?第一次在输出的第2行和第3行之间按下dropBomb时,也会有明显的延迟。
bombList在哪里构造?也许它在不同的线程中发生多次? –
请告诉我们'bombList'是什么类型? – OldCurmudgeon
@OldCurmudgeon我假设'ArrayList' – Divers