java向arrayList添加新对象不起作用
public abstract class Bee {
static Hive hive = Garden.hive;
protected int type;
protected int age;
protected int health = 3;
protected int getType()
{
return type;
}
protected int getAge()
{
return age;
}
protected int getHealth()
{
return health;
}
protected void setAge(int age)
{
this.age = age;
}
protected void setType(int input)
{
this.type = input;
}
protected abstract boolean eat();
protected abstract void anotherDay(); //the bees tasks for day (should include eat())
}
public class Queen extends Bee {
protected Queen()
{
setType(1);
}
protected int eggTimer = 0; // tracks when to add a new egg (not using age incase an external factor causes layEgg)
// removed code to avoid being too long
protected void layEgg() {
Egg egg = new Egg();
hive.addBee(egg); //fix??
eggTimer = 0;
}
}
import java.util.ArrayList;
class Hive {
ArrayList<Bee> beeList = new ArrayList<Bee>();
// code removed
public int beeIndex; // used to know what the index of bee you are in is
protected void addBee(Bee bee) { //Its running this and getting into the beelist.add(bee) but after there is nothing new in beeList.
if (beeList.size() < 100) {
beeList.add(bee);
} else {
System.out.println("Too many Bees to add more");
}
}
// removed code to avoid being too long
protected void anotherDay() {
int i = 0;
for (Bee bee : beeList) {
i++;
bee.anotherDay();
beeIndex = i;
}
}
}
代码运行时没有任何错误,但当它到达layEgg方法时,它会自动向配置单元中的arrayList添加一个egg(扩展bee的另一个类)。它运行addBee方法并遍历beeList。添加,但它仍然没有添加对象。如有任何建议,将不胜感激
我删掉了一些代码,使文章缩短了layEgg在Queen中第三次调用另一天()时的运行时间
public class Garden {
static Hive hive = new Hive();
protected int flowerIndex;
ArrayList<Flower> flowerList = new ArrayList<Flower>();
protected void anotherDay() {
int i = 0;
for (Flower flower : flowerList) {
i++;
flower.anotherDay();
flowerIndex = i;
}
}
protected void addHive(Hive hiveInput) {
Hive hive = hiveInput;
}
protected void addFlower(Flower flowerInput) {
Flower flower = flowerInput;
}
protected Flower getFlower(int input) {
return flowerList.get(input);
}
protected Flower findFlower() // finds the size of the arrayList and then
// creates a random number within the array
// to use as an index
{
int listSize = flowerList.size();
Random random = new Random();
int index = random.nextInt(listSize);
return flowerList.get(index);
}
protected int getFlowerListSize()
{
return flowerList.size();
}
}
# 1 楼答案
要检查的内容(使用断点或调试语句,或两者兼而有之)
我可以保证在Java中向列表中添加内容是有效的,因此您的代码是:
检查所有这些案例,缩小范围,直到找到原因