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);
First, define a class with any name 'SampleClass' and define a constructor method. The constructor will always have the same name as the class name and it does not have a return type. Constructors are used to instantiating variables of the class. Now, using the constructors we can assign values.
The quickest way to convert an array of objects to a single object with all key-value pairs is by using the Object. assign() method along with spread operator syntax ( ... ). The Object.
You can get the object at an index using obj = listName. get(index) and set the object at an index using listName. set(index,obj) . import java.
Core Java bootcamp program with Hands on practiceA list can be converted to a set object using Set constructor. The resultant set will eliminate any duplicate entry present in the list and will contains only the unique values. Set<String> set = new HashSet<>(list);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With