开发者

Dealing with ArrayLists in java...all members of the arraylist updating themselves?

I have a function that shrinks the size of a "Food bank" (represented by a rectangle in my GUI) once some of the food has been taken. I have the following function check for this:

public boolean tryToPickUpFood(Ant a)
    {
        int xCoord = a.getLocation().x;
        int yCoord = a.getLocation().y;
        for (int i = 0; i < foodPiles.size(); i++)
        {
            if (foo开发者_开发百科dPiles.get(i).containsPoint(xCoord, yCoord))
            {
                foodPiles.get(i).decreaseFood();
                return true;
            }
        }
        return false;
    }

Where decreaseFood shrinks the rectangle..

public void decreaseFood()
    {
        foodAmount -= 1;
        shrinkPile();
    }

    private void shrinkPile()
    {
        WIDTH -=1;
        HEIGHT = WIDTH;
    }

However, whenever one rectangle shrinks, ALL of the rectangles shrink. Why would this be?

edit:

Food piles are being added like such:

addFoodPile(new Food(new Point(200,200)));
addFoodPile(new Food(new Point(400,340)));

public void addFoodPile(Food fp)
    {
        foodPiles.add(fp);
    }


Because the same food pile is in each element of the array? If you are populating it like

FoodPile foodPile = new FoodPile();
for (int i = 0; i < count; i++) {
    foodPiles.add(foodPile)
    }

you should do this instead:

for (int i = 0; i < count; i++) {
    FoodPile foodPile = new FoodPile();
    foodPiles.add(foodPile)
    }

also, this loop:

for (int i = 0; i < foodPiles.size(); i++)
{
    if (foodPiles.get(i).containsPoint(xCoord, yCoord))
    {
        foodPiles.get(i).decreaseFood();
        return true;
    }
}

can be more readable if you use foreach syntax:

for (FoodPile foodPile : foodPiles)
{
    if (foodPile.containsPoint(xCoord, yCoord))
    {
        foodPile.decreaseFood();
        return true;
    }
}


This might be your problem -

private void shrinkPile()
{
    WIDTH -=1;
    HEIGHT = WIDTH;
}

In the standard Java naming convention, all uppercase names are used for static variables - since you haven't shown their declaration, I can't be sure - but it's certainly suspicious and a place to look.


I'm guessing you thought you were adding lots of separate piles into the List but actually you were adding a reference to the same one over and over. Check that part of your code.


From the code you have shown, it seems like the problem lies in where and how often the tryToPickUpFood() is used. Unless you've used the same reference of foodPiles, as pointed in the other answers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜