列表中的项目将被添加到列表中的最后一项替换

时间:2015-10-27 05:25:59

标签: java

这里我将不同的对象添加到列表中,但在检索列表时,我获取了最后添加的对象的内容

 @Override
        public String ConfirmOrder(OrderBean orderBean, ArrayList<CartBean> cartbean) {
            String response = "FAIL";
            OrderBean obean=null;
            try {
                ArrayList<OrderBean> list = new ArrayList<OrderBean>();

                orderBean.setOrderDate(new Date());
                orderBean.setOrderStatus("Pending");
                Iterator<CartBean> it = cartbean.iterator();
                while (it.hasNext()) {
                    CartBean type = (CartBean) it.next();
                    orderBean.setCartID(type.getCartID());
                    orderBean.setTotalPrice(type.getCost());
                    System.out.println("setting the cart id and price :"+type.getCartID()+" : "+type.getCost());//checking the items which were inserted into the object
                    obean=null;//setting the object to null every time 
                    obean=orderBean;
                    list.add(obean);
                    System.out.println("Cart count :");
                }
                //iterating the list
                for(OrderBean ob:list)
                {
                    System.out.println("cartid :"+ob.getCartID());
                }
}


here is the console output  

设置购物车ID和价格:1000:100.0
    购物车数量:
    设置购物车ID和价格:1001:90.0
    购物车数量:
    设置购物车ID和价格:1002:825.0
    购物车数量:
    设置购物车ID和价格:1003:1210.0
    购物车数量:

迭代相同的列表
   cartid:1003
   cartid:1003
   cartid:1003
   cartid:1003

1 个答案:

答案 0 :(得分:1)

这是因为,你不是都在创造一个对象。您将继续修改现有的

 while (it.hasNext()) {
                    CartBean type = (CartBean) it.next();
                    orderBean.setCartID(type.getCartID()); // here

实际上,每次在循环中都需要创建一个orderbean对象,然后将其添加到循环中。截至目前,您继续修改单个对象。