【问题标题】:How to set object value using List<Object> to a model class in java?如何使用 List<Object> 将对象值设置为 java 中的模型类?
【发布时间】:2014-12-25 03:00:21
【问题描述】:

如何使用 List 在我的模型中添加每个属性值?这就是我的工作

这是我的对象: 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("");

如何在我的 Item.java 中添加每个属性值?

我能做的是这样的:

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

【问题讨论】:

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

标签: java arrays arraylist


【解决方案1】:

除非我遗漏了什么,否则您只需将您的 mItem 添加到您的 List。喜欢

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

您还可以创建一个新的 Item 构造函数,看起来像

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

然后用单行添加like

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

【讨论】:

    【解决方案2】:

    为方便起见制作一个构造函数。

    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
    }
    

    从那时起,您可以通过

    轻松添加新的“项目”对象
    sBarang.add(new Item("101","Hammer",10));
    

    【讨论】:

      【解决方案3】:

      sBarang.add("") 不起作用。您尝试将 String 添加到仅包含 Item 对象的列表中。

      您帖子的后半部分听起来您正在寻找一种更有效的方法来为您的 Item 实例的字段分配值。通过向您的类添加构造函数来做到这一点。看起来像这样:

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

      像这样初始化你的项目:Item myItem = new Item("101", "Hammer", 10);

      像这样将它添加到您的列表中:sBarang.add(myItem);

      或使用单行:sBarang.add(new Item("101", "Hammer", 10));

      【讨论】:

        【解决方案4】:
         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...
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-12-07
          • 2018-11-12
          • 1970-01-01
          • 2019-10-17
          • 2021-09-11
          • 1970-01-01
          • 2013-06-17
          相关资源
          最近更新 更多