Java:动态填充数组(不是矢量/ ArrayList)
我想弄清楚是否有一些方法可以在不使用数组初始化的情况下动态地填充类中的对象数组。我真的想避免一行一行地填充数组。这有可能给我在这里的代码?Java:动态填充数组(不是矢量/ ArrayList)
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. 
    } 
} 
回答:
您可以使用HashMap<String,Attribute>
回答:
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]); 
回答:
attributes = new Attributes[sizeOfInput]; for (int i=0; i<sizeOfInput; i++) { 
    attributes[i] = itemList[i]; 
} 
此外,仅供参考,您可以添加东西到一个ArrayList,然后调用指定者()来获取对象的数组。
回答:
有很短的数组初始化语法:“你想输入的属性添加所有成员变量数组”
attributes = new Attribute[]{luck,speed,strength,etc}; 以上是 Java:动态填充数组(不是矢量/ ArrayList) 的全部内容, 来源链接: utcz.com/qa/257278.html
