Java:动态填充数组(不是vector / ArrayList) [英] Java: Dynamically Fill Array (not vector/ArrayList)
本文介绍了Java:动态填充数组(不是vector / ArrayList)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找出是否有某种方法可以动态填充类中的对象数组,而无需使用数组初始化。我真的很想避免逐行填充数组。
I'm trying to figure out if there's someway for me to dynamically fill an array of objects within a class, without using array initialization. I'd really like to avoid filling the array line by line. Is this possible given the code I have here?
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.
}
}
推荐答案
attributes = new Attributes[sizeOfInput];
for (int i=0; i<sizeOfInput; i++) {
attributes[i] = itemList[i];
}
此外,仅供参考,您可以将内容添加到ArrayList中,然后调用toArray()获取对象的数组。
Also, FYI you can add things to an ArrayList and then call toArray() to get an Array of the object.
这篇关于Java:动态填充数组(不是vector / ArrayList)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文