如何使用列表设置对象值<;对象>;到java中的模型类?

如何使用列表设置对象值<;对象>;到java中的模型类?,java,arrays,arraylist,Java,Arrays,Arraylist,如何使用列表在我的模型中添加每个属性值?我就是这么做的 这是我的目标: Item.java public class Item { private String code; private String name; private Integer qty; // skip the getter setter } 下面是我希望如何添加来自另一个类的值 List<Item> sBarang = new ArrayList<Item>(

如何使用列表在我的模型中添加每个属性值?我就是这么做的

这是我的目标: Item.java

public class Item {

    private String code;

    private String name;

    private Integer qty;

    // skip the getter setter
}
下面是我希望如何添加来自另一个类的值

List<Item> sBarang = new ArrayList<Item>();
sBarang.add("");

除非我遗漏了什么,否则您只需将
mItem
添加到
列表中即可。像

Item mItem = new Item(); // <-- instantiate a new Item.
mItem.setCode("101");
mItem.setName("Hammer");
mItem.setQty(10);
sBarang.add(mItem); // <-- add it to your List<Item>.
然后使用一行添加,如

sBarang.add(new Item("101", "Hammer", 10)); 

为了您的方便,创建一个构造函数

public class Item {
    public Item(String code, String name, int qty){
        this.code=code;
        this.name=name;
        this.qty=qty;
    }
    private String code;

    private String name;

    private Integer qty;

    //skip the getter setter
}
从那时起,您可以通过以下方式轻松添加新的“Item”对象

sBarang.add(new Item("101","Hammer",10));
sBarang.add(“”)不起作用。您正在尝试将
字符串
添加到仅包含
对象的列表中

文章的后半部分听起来像是在寻找一种更有效的方法来为
实例的字段赋值。为此,请向类中添加构造函数。看起来是这样的:

public class Item {

    public Item (String startCode, String startName, int startQty) {
        this.code = startCode;
        this.name = startName;
        this.qty = startQty;
    }
    ...
}
像这样初始化你的物品:
item myItem=newitem(“101”,“Hammer”,10)

将其添加到您的列表中,如下所示:
sBarang.Add(myItem)


或者使用一行:
sBarang.add(新项目(“101”,“锤子”,10))

不确定你在问什么
sBarang.add(mItem)
是将项目添加到项目列表中的方式。您不能将单个项目值添加到项目列表中,因为它是一个项目列表,而不是字符串/整数等。如果您有一个对象列表,则需要单独设置它们,并希望它们的顺序正确。你具体想做什么?
sBarang.add(new Item("101","Hammer",10));
public class Item {

    public Item (String startCode, String startName, int startQty) {
        this.code = startCode;
        this.name = startName;
        this.qty = startQty;
    }
    ...
}
 Item m= new Item(); 
    m.Set_Code("101");
    m.set_Name("Hammer");
    m.set_Qty(10);
    s_barang . add(m); 
    i need to store the next value but always i get the last value in the array how to clear the current data from model class object and push the next item into m...