我有一个功能,可以在取走一些食物后缩小“食物银行”(在我的 GUI 中用矩形表示)的大小。我对此进行了以下功能检查:
public boolean tryToPickUpFood(Ant a)
{
int xCoord = a.getLocation().x;
int yCoord = a.getLocation().y;
for (int i = 0; i < foodPiles.size(); i++)
{
if (foodPiles.get(i).containsPoint(xCoord, yCoord))
{
foodPiles.get(i).decreaseFood();
return true;
}
}
return false;
}
在 decreaseFood 缩小矩形的地方..
public void decreaseFood()
{
foodAmount -= 1;
shrinkPile();
}
private void shrinkPile()
{
WIDTH -=1;
HEIGHT = WIDTH;
}
但是,每当一个矩形缩小时,所有矩形都会缩小。为什么会这样?
编辑:
食物堆是这样添加的:
addFoodPile(new Food(new Point(200,200)));
addFoodPile(new Food(new Point(400,340)));
public void addFoodPile(Food fp)
{
foodPiles.add(fp);
}
最佳答案
因为同一个食物堆在数组的每个元素中?如果你像这样填充它
FoodPile foodPile = new FoodPile();
for (int i = 0; i < count; i++) {
foodPiles.add(foodPile)
}
你应该这样做:
for (int i = 0; i < count; i++) {
FoodPile foodPile = new FoodPile();
foodPiles.add(foodPile)
}
另外,这个循环:
for (int i = 0; i < foodPiles.size(); i++)
{
if (foodPiles.get(i).containsPoint(xCoord, yCoord))
{
foodPiles.get(i).decreaseFood();
return true;
}
}
如果使用 foreach 语法,可读性更好:
for (FoodPile foodPile : foodPiles)
{
if (foodPile.containsPoint(xCoord, yCoord))
{
foodPile.decreaseFood();
return true;
}
}
关于java - 在 java 中处理 ArrayLists...arraylist 的所有成员都在更新自己?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2527722/