我正在尝试使用Detail Class中的所有这些值创建一个Array。有没有更好的方法来创建这个数组?
Details[] DetailsArray = new Details[10];
Details Details = new Details();
Details Details2 = new Details();
Details Details3 = new Details();
Details Details4 = new Details();
Details Details5 = new Details();
Details Details6 = new Details();
Details.setNumber(new Integer(1));
Details2.setEmployeeID(new Double(300));
Details3.setCurrency("Euro");
Details4.setSize(new Double (400));
Details5.setEvent("Something");
Details6.setId(new Integer(10));
DetailsArray[0] = Details;
DetailsArray[1] = Details2;
DetailsArray[2] = Details3;
DetailsArray[3] = Details4;
DetailsArray[4] = Details5;
DetailsArray[5] = Details6;
System.out.println(DetailsArray);
EmployeeDetails.setDetails(DetailsArray);
答案 0 :(得分:0)
说实话,这是非常奇怪的代码,但这可行:
// Why are you creating an array with 10 elements but only using 6?
Details[] detailsArray = new Details[10];
for (int i = 0; i < 6; i++) {
detailsArray[i] = new Details();
}
detailsArray[0].setNumber(new Integer(1));
detailsArray[1].setEmployeeID(new Double(300));
detailsArray[2].setCurrency("Euro");
detailsArray[3].setSize(new Double (400));
detailsArray[4].setEvent("Something");
detailsArray[5].setId(new Integer(10));
你真的想要在每个对象上设置不同的属性吗?您确定确实想要在单个对象上设置多个属性吗?
答案 1 :(得分:0)
您可以使用列表而不是数组,但如果我理解您要实现的目标,您可能需要这样做,而details
对象包含该员工的所有信息:
Details details = new Details();
details.setNumber(new Integer(1));
details.setEmployeeID(new Double(300));
details.setCurrency("Euro");
details.setSize(new Double (400));
details.setEvent("Something");
details.setId(new Integer(10));
System.out.println(details);
EmployeeDetails.setDetails(details);
答案 2 :(得分:0)
使用for
循环?
Details[] detailsArray = new Details[10];
for (int i = 0; i < detailsArray.length; i++)
detailsArray[i] = new Details();
detailsArray[0].setNumber(New Integer(1));
...
那就是说...在实际代码中很少会有一个静态数组,你手动填充这个数组。如果你这样做了,你可能希望在外部文件中拥有这些对象的数据,或者完全是其他数据结构。
答案 3 :(得分:0)
创建接受所有必需参数的构造函数。然后做这样的事情:
deatilsArray = new DetailsArray [] { 新细节(1,300,“Euro”,400,“Something”), 新细节(2,400,“美元”,500,“其他”), .................. };
或者,您可以创建其他类DetailsBuilder来启动详细信息字段:
Details d =
new DetailsBuilder().create().setName("aaa").setEmployeeId(123).setCurrency("Euro").getInstance();
在这种情况下,上面的代码如下所示:
DetailsBuilder builder = new DetailsBuilder();
deatilsArray = new DetailsArray[] {
builder.create().setName("aaa").setEmployeeId(123).setCurrency("Euro").getInstance(),
builder.create().setName("bbb").setEmployeeId(123).setCurrency("Euro").getInstance(),
};
BTW根据java命名约定变量名称始终以小写字母开头。
答案 4 :(得分:0)
使用临时内部类的解决方案。
class Pwn {
final Details d = new Details();
}
Details[] detailsArray = new Details[] {
(new Pwn (){{ d.setNumber(new Integer(1)); }}).d,
(new Pwn (){{ d.setEmployeeID(new Double(300)); }}).d,
(new Pwn (){{ d.setCurrency("Euro"); }}).d,
(new Pwn (){{ d.setSize(new Double (400)); }}).d,
(new Pwn (){{ d.setEvent("Something"); }}).d,
(new Pwn (){{ d.setId(new Integer(10)); }}).d
}
:)