'Index 5 out of bounds for length 5 when trying to add an element to an array of objects [duplicate]
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
