我正在试图弄清楚是否有些动态填充类中的对象数组,而不使用数组初始化。我真的想避免逐行填充数组。根据我在这里的代码,这可能吗?
final class Attributes {
private final int TOTAL_ATTRIBUTES = 7;
Attribute agility;
Attribute endurance;
Attribute intelligence;
Attribute intuition;
Attribute luck;
Attribute speed;
Attribute strength;
private Attributes[] attributes; //array to hold objects
private boolean initialized = false;
public Attributes() {
initializeAttributes();
initialized = true;
store(); //method for storing objects once they've been initialized.
}
private void initializeAttributes() {
if (initialized == false) {
agility = new Agility();
endurance = new Endurance();
intelligence = new Intelligence();
intuition = new Intuition();
luck = new Luck();
speed = new Speed();
strength = new Strength();
}
}
private void store() {
//Dynamically fill "attributes" array here, without filling each element line by line.
}
}
答案 0 :(得分:2)
attributes = new Attributes[sizeOfInput];
for (int i=0; i<sizeOfInput; i++) {
attributes[i] = itemList[i];
}
此外,您可以将内容添加到ArrayList,然后调用toArray()以获取该对象的数组。
答案 1 :(得分:1)
有一个简短的数组初始化语法:
attributes = new Attribute[]{luck,speed,strength,etc};
答案 2 :(得分:0)
Field[] fields = getClass().getDeclaredFields();
ArrayList<Attrubute> attributesList = new ArrayList<Attrubute>();
for(Field f : fields)
{
if(f.getType() == Attrubute.class)
{
attributesList.add((Attrubute) f.get(this));
}
}
attributes = attributesList.toArray(new Attrubute[0]);
答案 3 :(得分:-1)
您可以使用HashMap<String,Attribute>