-1

Here I am adding different objects to the list,but while retrieving the list i'm getting the contents of the object which is added at last

 @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  

setting the cart id and price :1000 : 100.0
Cart count :
setting the cart id and price :1001 : 90.0
cart count :
setting the cart id and price :1002 : 825.0
Cart count :
setting the cart id and price :1003 : 1210.0
Cart count :

iterating the same list
cartid :1003
cartid :1003
cartid :1003
cartid :1003

1 Answers1

1

It's because , you are not all creating an object. You are keep on modifying the existing one

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

Actually you need to create an orderbean object each time in the loop and then add it to loop. As of now you keep on modifying single object.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307