zeboidlund
zeboidlund

Reputation: 10137

Java: Dynamically Fill Array (not 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.
    }
}

Upvotes: 1

Views: 3632

Answers (4)

Nathan Romano
Nathan Romano

Reputation: 7096

You can use a HashMap<String,Attribute>

Upvotes: -1

Bala R
Bala R

Reputation: 108957

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

Upvotes: 0

jiggy
jiggy

Reputation: 3826

There is a short Array initialization syntax:

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

Upvotes: 1

Rocky Pulley
Rocky Pulley

Reputation: 23301

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.

Upvotes: 3

Related Questions