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
1 Answer 1
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
Achrome
7,82114 gold badges38 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-java