-1

I have three arraylist(int, string, and one more string) in one class. In the other class I the code that loops through all three it looks like this:

public class ArrayContainer<T> implements ArrayContainerInterface<T> {
private T[] container;
private int defaultSize = 25;
private int numItems;

public ArrayContainer() {
    container = (T[]) new Object[defaultSize];
    numItems =0;
}

@Override
public void add(T item) {

    if (numItems < defaultSize) 
    { 
        container[++numItems] = item;

    } 


}

@Override
public boolean isFull() {
    return false;
}

@Override
public String toString() {
    String output = new String();
    for (int i=0; i < defaultSize; i++) {
        output += container[i];
    }

    return output;  
  }
}

the stack trace that i'm getting looks like this:

null01234567891011121314151617181920212223
The number container object is NOT full!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 25
at ArrayContainer.add(ArrayContainer.java:17)
at ArrayContainerDriver.main(ArrayContainerDriver.java:31)

what exactly is wrong with my code that is giving me an error like this?

The link to my GitHub and to the rest of my classes are here

FlapNarp
  • 3
  • 2

1 Answers1

2

As Steve wrote in the comment, you need to change:

container[++numItems] = item;

to

container[numItem++] = item

And the reason for that is that with ++numItems you first increment the numItems and then add the item. That would cause an Out Of Bound Exception because on the last item you add it to the 25th place (out of the array size)

Shaked Eyal
  • 123
  • 1
  • 14