pianos pianos - 4 months ago 5x
Java Question

Setting value in Java array returns error

This method is supposed to set a value in an array, given its index. The error is an

, which occurs on the line:

GrowingArray [index] = value;

However, I've done some research and using
array [index] = value
seems to be a legitimate way to set a value in an array. A pointer in the right direction would be helpful.

public void set (int index, int value) {
if (index <= GrowingArray.length) {
GrowingArray[index] = value;
} else {
int [] destination = new int [12/10*GrowingArray.length];
destination [index] = value;
System.arraycopy(destination, 0, GrowingArray, 0, destination.length);


Java arrays have 0 based indices (like 99% of things in computer science), so checking <= (instead that < ) will allow, for example the index 4 for an array of size 4, which will end out of bonds.

if (index <= GrowingArray.length){
  GrowingArray[index] = value;

In addition 12/10 is an integer division which yields 1, if you want to increase capacity by 20% you should use float values, eg:

int newCapacity = (int)(oldCapacity*1.2f);