我试图定义一个称为add()的方法,该方法将对象Fish添加到数组fish []中。不使用arrayList怎么办?我不断收到错误:
线程“主”中的异常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;}
}
最佳答案
这里是动态数组解决方案,它是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;
}
}