简体   繁体   中英

How to set object value using List<Object> to a model class in java?

how do add each property value in my model using List? Here is what i do

here is my object : Item.java

public class Item {

    private String code;

    private String name;

    private Integer qty;

    // skip the getter setter
}

here is how i want to add the value from another class

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

How do I add each property value my Item.java?

What I can do is something like this :

Item mItem = new Item();
mItem .setCode("101");
mItem .setName("Hammer");
mItem .setQty(10);

Unless I'm missing something you just need to add your mItem to your List . Like

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

You could also create a new Item constructor that looks something like

public Item(String code, String name, Integer qty) {
    this.code = code;
    this.name = name;
    this.qty = qty;
}

and then use a single line add like

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

Make a constructor for your convenience.

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
}

Since then, you can add new "Item" object easily by

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

sBarang.add("") is not going to work. Your trying to add a String to a list containing only Item objects.

The second half of your post sounds like you're looking for a more efficient way to assign values to the fields of your Item instance. Do this by adding a constructor to your class. That will look like this:

public class Item {

    public Item (String startCode, String startName, int startQty) {
        this.code = startCode;
        this.name = startName;
        this.qty = startQty;
    }
    ...
}

Initialize your item like this: Item myItem = new Item("101", "Hammer", 10);

Add it to your list like this: sBarang.add(myItem);

Or use the one-liner: sBarang.add(new Item("101", "Hammer", 10));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM