0
for(int i=0;i<Stockhouse.total_stocks;i++){
 buyers.clear();
 for(int j=0; j<buy.size();j++){
 if(buy.get(j).stock_Id.equals("Stock"+i)){
 System.out.println("Agent "+buy.get(j).ID+",stock"+buy.get(j).stock_Id+",price "+buy.get(j).price +",quant "+buy.get(j).quantity);
 Auctionhouse buypr= new Auctionhouse(buy.get(j).price,buy.get(j).quantity);
 buyers.add(buypr);
 }
 }
 total_buy.add(buyers);
 System.out.println("buy size "+total_buy.get(i).size());
 }

here the buy size shows me correctly the size of each ArrayList as an elements of total_buy ArrayList.

My problem is that after when i need these sizes again,i only get the size of the last ArrayList.

 total_buy.get(0).size()=3
 total_buy.get(1).size()=3
 total_buy.get(2).size()=3.......

but only total_buy.get(2).size()=3 is actually 3!

LGAP
2,49317 gold badges51 silver badges74 bronze badges
asked Feb 23, 2013 at 11:19

1 Answer 1

4

You are reusing the same object, and the reference is getting added to the total_buy list. Instead of

buyers.clear();

do

buyers = new ArrayList<Auctionhouse>();

This will create a new object for buyers every time, and therefore keep updated references in the total_buy list.

answered Feb 23, 2013 at 11:31
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.