Java对象未添加到ArrayList

时间:2013-05-04 17:15:58

标签: java arraylist immutability mutable

我有问题。我正在为鱼类生态系统编写代码,我正在尝试将新的Fish对象添加到现有的鱼ArrayList中。但是,当我检查ArrayList时,结果是空的?想法?

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;
                }

            }

1 个答案:

答案 0 :(得分:0)

每次创建一个新的ArrayList:ArrayList<Fish> fishplusone = new ArrayList<Fish>(fish.size());

首先进行检查然后将其添加到现有列表是否更容易?