[Solved] I am new in using ArrayLists. Array Out of Bounds, Array seems to be empty, but have been adding Strings to it already


First of all, and that’s supposed to solve the problem. If you use an ArrayList you should check its documentation. When you supposed to go through a simple array you use “nameOfArray.length”, right? Well, the ArrayList has the method “.size()” which bascialy has the same use.
So your loop would be better this way :

for(int i=0; i<pizza.toppings.size();i++){
    System.out.println(pizza.toppings.get(i));
}

This way you’re sure you’ll never get out of your array’s length.

Now of course there is still a problem with your value. And it’s hard to tell where it is for two reasons :

  1. We miss the important parts of your code (such as the constructor)

  2. Because the pizza.toppingctr is public and shouldn’t be.

You’d better increment it in your count() method and have it private.
And in fact, if you use the “.size()” method, you shouldn’t need it at all.

solved I am new in using ArrayLists. Array Out of Bounds, Array seems to be empty, but have been adding Strings to it already