我这里有10个物品,但是我还需要更多的物品,还有更短的方法吗?
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);
答案 0 :(得分:5)
你可以避免所有作业,但我担心它不会短得多:
<p id="spy-on-me">
some text
<p>
这比你的技术略有优势:
显然,这假设在初始化期间数组完全填充。
答案 1 :(得分:0)
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()
样板。
答案 2 :(得分:0)
考虑使用静态工厂方法而不是构造函数。
它给你一些好处:
实施
class Gato {
private boolean field1;
private String field2;
private String field3;
private int field4;
private Gato (boolean field1, String field2, String field3, int field4) {
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
this.field4 = field4;
}
public static Gato newInstance (boolean field1, String field2, String field3, int field4) {
return new Gato(field1, field2, field3, field4);
}
因此,在您的方法中,您将使用该实现
gato[0] = Gato.newInstance(true, "Siames", "Fluffy", 10);