PrasoonMishra PrasoonMishra - 1 month ago 5
Java Question

Add method in ArrayList in Java

I am using

ArrayList
to store the values of Quantity entered by user in shopping cart. But while trying to add the quantity to
ArrayList
, the quantity is not being added. Why is quantity not being added?

The code is here:

public class Add_Cart1 extends HttpServlet {

String id, name, cost, stock;
ArrayList qty = new ArrayList();

if(id != null)
{
for(j = 0; j < qty.size(); j++)
{
System.out.println("values......." + req.getParameterValues("qty"));
System.out.println("qty........." +
qty.add(req.getParameterValues("qty")));

}
}
}

Answer

Your qty.add() is inside this for loop:

          for(j=0;j<qty.size();j++)

But qty.size() is 0 because you haven't added anything to the list yet. So nothing ever gets added.

Also, the add() method always returns boolean. Are you sure you're not looking for the get() method?