在没有arrayList的情况下向数组添加元素

时间:2014-01-31 23:40:38

标签: java arrays object

我正在尝试定义一个名为add()的方法,该方法将一个对象Fish添加到数组fish []中。如何在不使用arrayList的情况下解决这个问题?我一直收到错误: 线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:1

public class Pond {
private Fish[] fish;
private int numFish ;
private int capacity;

public Pond(int capacity){
    this.capacity = capacity;
}
public int getNumFish(){ return numFish;
}
public boolean isFull(){//Ponds can only have so many fish
    boolean Full = false;
    if (numFish >= capacity){
        Full = true;}
    return Full;
}
public void add(Fish aFish) {// puts a fish in the pond--OR-- replaces a fish that has been temporarily removed 
    if (numFish < capacity){
        fish[numFish++] = aFish;}
}

2 个答案:

答案 0 :(得分:1)

这里是动态数组解决方案,它是ArrayList方法的简单实现。

public void add(Fish aFish) {
    ensureCapacity();
    fish[numFish++] = aFish;
}

private void ensureCapacity() {
    if (numFish == fish.length) {
        int newSize = fish.length * 2;
        Fish[] newFish = new Fish[newSize];

        System.arraycopy(fish, 0, newFish, 0, fish.length);
        fish = newFish;
    }
}

答案 1 :(得分:0)

在池塘构造函数中,您可以添加fish = new Fish[capacity]以将鱼群的初始大小设置为池塘的容量。请记住,您无法向数组添加值,只能更改已存在的值。