我这里有10个对象,但是我必须初始化20个以上的对象,有没有更短的方法呢?
Gallina[] gallina=new Gallina[10];
gato[0]=new Gato(true, "Siames", "Fluffy", 10);
gato[1]=new Gato(false, "Persa", "Fluffy", 11);
gato[2]=new Gato(true, "Maine Coon", "Fluffy", 9);
gato[3]=new Gato(false, "Ragdoll", "Fluffy", 4);
gato[4]=new Gato(false, "Bengala", "Fluffy", 1);
gato[5]=new Gato(true, "Sphynx", "Fluffy", 6);
gato[6]=new Gato(true, "Abisinio", "Fluffy", 3);
gato[7]=new Gato(false, "Azulruso", "Fluffy", 9);
gato[8]=new Gato(true, "Siberiano", "Fluffy", 2);
gato[9]=new Gato(true, "Siames", "Fluffy", 4);
最佳答案
class Gallina {
private int gatoIndex = 0;
private Gato[] gatos;
public Gallina(int gatosLength) {
gatos = new Gato[gatosLength];
}
public void addGato(boolean state, String name, String type, int value) {
if (gatoIndex > gatos.length) {
// an exception probably or resize array
}
gatos[gatoIndex] = new Gato(state, name, type, value);
gatoIndex += 1;
}
}
class Test {
public static void main(String[] args) {
Gallina gallina = new Gallina(10);
gallina.addGato(true, "ABC", "Fluffy", 10);
}
}
使用
List<Gato>
代替Gato[]
将帮助您摆脱gatoIndex
并自行调整数组大小。基本上,使用上面的方法,您不必每次都编写相同的
new Gato()
样板。