-2

I have a problem. I am writing code for an ecosystem with fish and I am trying to add a new Fish object to an existing fish ArrayList . However, when I check the ArrayList it turns out to be empty? Thoughts?

public void addFish(Fish f){
    ArrayList<Fish> fishplusone = new ArrayList<Fish>(fish.size());
    if (landscape[f.getRow()][f.getCol()] != ROCK) {
        for (Fish otherfish: this.fish) {
                if(otherfish.getRow() == f.getRow() && otherfish.getCol() == f.getCol()) {
                    throw new IllegalFishPositionException(IllegalFishPositionException.TWO_FISH_IN_ONE_PLACE); 

                }
                else {
                    fishplusone.add(otherfish); 
                    }
                fishplusone.add(f);
                fish = fishplusone;
                }

            }
anubie
  • 21
  • 1
  • 1
    Please edit your post so that it's sensibly indented, and remove extraneous code. Ideally, you should show a short but *complete* program demonstrating the problem. We've no idea what the `fish` variable is, for example. – Jon Skeet May 04 '13 at 17:17
  • 1
    Maybe `landscape[f.getRow()][f.getCol()]` is a `ROCK` or `this.fish` is empty (assuming you don't get any exceptions). – assylias May 04 '13 at 17:17
  • does it always throw the exception? – Kevin Bowersox May 04 '13 at 17:18
  • no it compiles without throwing any exceptions but the fish arraylist is empty – anubie May 04 '13 at 17:22
  • if this.fish is empty wouldn't one fish still be added to the arraylist? – anubie May 04 '13 at 17:24
  • No, if there are no objects in an List an enhanced for will not be executed. – Aaron May 04 '13 at 17:33

1 Answers1

0

You create a new ArrayList each time: ArrayList<Fish> fishplusone = new ArrayList<Fish>(fish.size());

Isn't it easier to do your checks first and then add it to an existing List?

Aaron
  • 826
  • 10
  • 22