Java: Dynamically Fill Array (not vector/ArrayList)

落爺英雄遲暮 提交于 2020-03-05 08:18:30

问题


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.
    }
}

回答1:


attributes = new Attributes[sizeOfInput];

for (int i=0; i<sizeOfInput; i++) {
    attributes[i] = itemList[i];
}

Also, FYI you can add things to an ArrayList and then call toArray() to get an Array of the object.




回答2:


There is a short Array initialization syntax:

attributes = new Attribute[]{luck,speed,strength,etc};



回答3:


 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]);



回答4:


You can use a HashMap<String,Attribute>



来源:https://stackoverflow.com/questions/6458463/java-dynamically-fill-array-not-vector-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!