0

i'm working in java arrays, and i get this exception

java.lang.IndexOutOfBoundsException:Index: 0, Size: 0

here is my code :

public static void main(String[] args) {

    setData();

}

public static void setData() {

    try {

        Product[] products = null;

        int size = getSize();

        for(int i = 0; i < size; i++) {

            products = new Product[i];

            if(products.length > 1) {
                products[i].setId(i);
            }

        }

    } catch(Exception e) {
        System.out.println(e.getMessage());
    }
}

so, what's wrong ?

uzx 619
  • 1
  • 6
  • 1
    `products = new Product[i];` What's this line supposed to do? In your first iteration `i` is 0 and thus you're creating an array with length 0. – QBrute May 04 '19 at 17:19
  • So you are recreating your `products` array for each iteration of your loop on the line that says: products = new Product[i]; Is this really what you want to do? and as @QBrute mentioned above, when you create an array with length 0 ( for i=0), accessing it is going to give you an exception – gbenroscience May 04 '19 at 17:19
  • @gbenroscience no, i want to create it one time and make the length of this array = i, but i don't know how – uzx 619 May 04 '19 at 17:22
  • 1
    Simple: an array of size 0 is empty. An empty array has no data at index 0. Just read that exception message aloud to yourself a few times. The message contains all the information information you need to start fixing your code. – GhostCat May 04 '19 at 17:22
  • For your code to make any sense, you need to give the array a fixed length, do this outside the for-loop. A good candidate for the fixed length would be the `size` variable `int size = getSize();` ...depending on what you are trying to do. – gbenroscience May 04 '19 at 17:25
  • Also you are not adding any Product per se to the array, so a NullPointerException trap would still be waiting for you after you have fixed the evil IndexOutOfBoundsException – gbenroscience May 04 '19 at 17:27
  • 1
    @gbenroscience yes i got it lol :) – uzx 619 May 04 '19 at 17:31
  • @uzx 619 I hear you. Enjoy – gbenroscience May 04 '19 at 17:33

0 Answers0