gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:32:21 25 4
gpt4 key购买 nike

我正在尝试定义一个名为 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;}
}

最佳答案

这里是动态数组解决方案,它是 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;
}
}

关于java - 在没有 arrayList 的情况下向数组添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21492107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com