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!

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.