微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决Java:动态填充数组不是vector / 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.
    }
}
    

解决方法

        
attributes = new Attributes[sizeOfInput];

for (int i=0; i<sizeOfInput; i++) {
    attributes[i] = itemList[i];
}
另外,仅供参考,您可以将内容添加到ArrayList中,然后调用toArray()以获取对象的Array。     ,        有一个简短的数组初始化语法:
attributes = new Attribute[]{luck,speed,strength,etc};
    ,        
 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]);
    ,        你可以用a4ѭ     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。