[英]ArrayList of ArrayLists
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. 在这里,购买大小向我正确显示了每个ArrayList的大小,作为total_buy ArrayList的元素。
My problem is that after when i need these sizes again,i only get the size of the last ArrayList. 我的问题是,当我再次需要这些大小时,我只会得到最后一个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! 但只有total_buy.get(2).size()= 3实际上是3!
You are reusing the same object, and the reference is getting added to the total_buy
list. 您正在重用同一对象,并且引用已添加到
total_buy
列表中。 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. 每次都会为
buyers
创建一个新对象,因此total_buy
更新的参考保留在total_buy
列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.