【问题标题】:Java: Dynamically Fill Array (not vector/ArrayList)Java:动态填充数组(不是向量/ArrayList)
【发布时间】:2011-09-21 10:56:09
【问题描述】:

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

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

【问题讨论】:

  • 只是为了澄清......“你想将所有成员变量类型的属性添加到数组中吗?”这就是你所说的动态rt?
  • 我想你想自己实现任何已经在Java Collection中实现的东西,你可以看看OpenJDK,看看他们是怎么做到的。

标签: java arrays dynamic


【解决方案1】:
attributes = new Attributes[sizeOfInput];

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

另外,仅供参考,您可以将内容添加到 ArrayList,然后调用 toArray() 以获取对象的 Array。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 虽然反射“解决”了这里的问题,但这里更可能是设计问题 :) 使用 getDeclaredFields 可能会更好地处理非公共领域。
    • @mihi 我无法对设计发表评论,但使用getDeclaredFields() 确实有意义。
    • 我不明白的一点是..为什么我不只使用数组来传输值,而不是使用ArrayList?
    • @Holland 数组不能像 ArrayList 那样动态增长。如果您将拥有固定数量的属性,您可以声明一个该大小的数组并使用它。
    【解决方案4】:

    您可以使用HashMap&lt;String,Attribute&gt;

    【讨论】:

    • HashMap 在这种情况下有什么帮助?
    • 其他人都有代码示例,也许你也可以扔一个
    • 这真的是评论,而不是问题的答案。请使用“添加评论”为作者留下反馈。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    相关资源
    最近更新 更多