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

how to add each property value in my model using List? That's what I'm doing

here is my object: Item.java

public class Item {

    private String code;

    private String name;

    private Integer qty;

    // skip the getter setter
}

this is how i want to add value from another class

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

How to add each value of the property my Item.java?

What I can do is something like this:

Item mItem = new Item();
mItem .setCode("101");
mItem .setName("Hammer");
mItem .setQty(10);
+4
source share
3 answers

If I am missing something, you just need to add mItemto yours List. how

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 can also create a new constructor Itemthat looks something like

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

and then use one line by adding as

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

.

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));
+2

sBarang.add("")will not work. Your attempt to add Stringto a list containing only objects Item.

The second half of your message sounds like you're looking for a more efficient way to assign values ​​to the fields of your instance Item. Do this by adding a constructor to your class. It 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 element as follows: Item myItem = new Item("101", "Hammer", 10);

Add it to your list as follows: sBarang.add(myItem);

Or use single line: sBarang.add(new Item("101", "Hammer", 10));

+1
source

Source: https://habr.com/ru/post/1568940/


All Articles