-2

I'm trying to implement this interface but when I run through the tester I receive.

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 4 at ListOfStrings.addLast(ListOfStrings.java:75)"

Any idea how I could change addLast?

/**
 * Adds the given element to the end of this list.
 *
 * @param str element to be added to the end of this list
 */
@Override
public void addLast(String str) {
    list[SIZE] = str;
    SIZE++;

}
khelwood
  • 55,782
  • 14
  • 81
  • 108
Kingjp
  • 11
  • 1
  • You could assign to an index that is less the length of your array. – khelwood Feb 15 '22 at 21:45
  • If the array has a length of 4, the highest index you can access is 3. No idea how your code ended up accessing index 6. In the context of `addLast`, `SIZE` was `6` for some reason, why? – f1sh Feb 15 '22 at 21:45
  • Run through your code with a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to understand why `SIZE` is going out of bounds. – Alias Cartellano Feb 15 '22 at 21:58

1 Answers1

0

In java, arrays are defined as a set size, which cannot be changed. It looks like you're trying to add too many elements to the array. You would need to check to see if you can add any more elements to the array, via something like if (index < list.size) {...} before you actually add another element.

Alternatively, if you need the array to be able to grow indefinitely, you could use an ArrayList, or another dynamically allocated structure like linked lists. You can find details for ArrayLists in java here

Charlie
  • 136
  • 1
  • 8