0

This method is supposed to set a value in an array, given its index. The error is an ArrayIndexOutOfBoundsException, 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);
  }
}

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I didn't realize that <= allowed my array check to go out of bounds. I changed it to < as you said to, and the error is gone.
1

in java array's index start with 0,

so when index == GrowingArray.length, the max index of GrowingArray is [index - 1]

what about try to change

if (index <= GrowingArray.length)

to

if (index < GrowingArray.length){

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.