0
public static Groceries [] addGrocery(Groceries[] arr, String name, int price) {
        int arrayLength = Array.getLength(arr);
        System.out.println(arrayLength);
        Groceries[] newGrocery = new Groceries[arrayLength + 1];
        int arrayLength2 = Array.getLength(newGrocery);
        System.out.println(arrayLength2);
        int i;
        for(i = 0; i < arrayLength; i++) {
            newGrocery[i] = arr[i];
            System.out.println("New item added" + i);
        }
        newGrocery[i+1] = new Groceries(name, price);
        return newGrocery;

    }

I have this method where I input an array containing 4 objects and it creates a new array of objects copying the previous 4 objects and then adding one more to the array. But I keep getting this exception.

  • 1
    `Array.getLength(newGrocery)` why not just `newGrocery.length`? – Andy Turner Mar 10 '22 at 14:20
  • 3
    You need to write `newGrocery[i] = new Groceries(name, price);` because `i` has already been increased 4 times in the loop. Increasing it again with `i + 1` will get you out of range for the new array. It would be better to write `newGrocery[newGrocery.length - 1] = new Groceries(name, price);` instead, so that you're not dependent on `i` – QBrute Mar 10 '22 at 14:24
  • 1
    Note: always have variables with the smallest scope possible. For example: declare your loop counters WITHIN the for loop `for (int i ...)` ... because that ENSURES that you won't use that `i` afterwards. And just for the record: as you seem to be allowed to use library methods from the Array class ... that class has a method that copies content from one array into another. There is no need to do that manually. Besides learning how to loop arrays and not go "off by one" in the end. – GhostCat Mar 10 '22 at 14:32

1 Answers1

0

The exception occurred because you're trying to add an element to an array index (i+1) that just doesn't exist, here:

newGrocery[i+1] = new Groceries(name, price);

Its because i has already been incremented by the for loop at the end to the last index value in the array, by doing i+1 you're trying to access the index = arrayLength2 which doesn't exist.

May be what you want is a List that is capable of expanding its size when a new element is added, unlike array which has a fixed size.

Osama A.Rehman
  • 912
  • 1
  • 6
  • 12