首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java:动态填充数组(不是vector/ArrayList)

Java:动态填充数组(不是vector/ArrayList)
EN

Stack Overflow用户
提问于 2011-06-24 01:53:24
回答 4查看 3.2K关注 0票数 1

我正在尝试找出是否有某种方法可以在不使用数组初始化的情况下动态填充类中的对象数组。我真的希望避免逐行填充数组。考虑到我这里的代码,这是可能的吗?

代码语言:javascript
复制
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.
    }
}
EN

回答 4

Stack Overflow用户

发布于 2011-06-24 02:05:03

代码语言:javascript
复制
attributes = new Attributes[sizeOfInput];

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

此外,仅供参考,您可以将对象添加到数组中,然后调用toArray()来获取对象的ArrayList。

票数 3
EN

Stack Overflow用户

发布于 2011-06-24 02:05:54

有一个简短的数组初始化语法:

代码语言:javascript
复制
attributes = new Attribute[]{luck,speed,strength,etc};
票数 1
EN

Stack Overflow用户

发布于 2011-06-24 02:02:26

代码语言:javascript
复制
 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]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6458463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档