user3085046
user3085046

Reputation: 11

Error : “Thread-1” java.lang.IndexOutOfBoundsException

I have some code for a trivia/unscramble bot which ran inside a server in which the user tries to guess the answer to a question before the time is up. The code compiles fine however after running the thread for about 30-45 minutes, I get an error and the trivia stops working. Here is the error I get:

Exception in thread "Thread-1" java.lang.IndexOutOfBoundsException: 
  Index: 973, Size 965
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at org.emulinker.kaillera.model.impl.Trivia.run(Trivia.java:251)
    at java.lang.Thread.run(Unknown Source)

Here is the code for org.emulinker.kaillera.model.impl.Trivia, starting at line 249:

        else{
            temp = generator.nextInt(questions.size() - 1);
            questions_count = questions_num.get(temp);
            questions_num.remove(temp);
        }

Any idea on how to fix this issue?

Upvotes: 0

Views: 753

Answers (2)

paxdiablo
paxdiablo

Reputation: 882028

I'm not sure what other information Java could give you to make this any easier.

It tells you the exact line Trivia.java:251, the collection size 965 and the index you're trying to use 973. Surely that's enough to be getting on with?

Normally there'd be little chance of me trying to figure out which of those several hundred lines is line 251, however, I'm bored at the moment so I'll give it a shot (and, in any case, you've since replaced the massive code dump with just the relevant lines). The errant line appears to be:

 else{
     temp = generator.nextInt(questions.size() - 1);
     questions_count = questions_num.get(temp);       // << THIS ONE
     questions_num.remove(temp);
 }

Now I'm not going to go through the entirety of your "War and Peace"-style code snippet that you seem to think satisfies the "smallest example that exhibits the problem" :-)

But I'd say it's a safe bet that questions and questions_num have diverged in size somewhere, assuming they even were the same size at some point in the past. Quite possibly they've diverged due to that third line in the else block above or, more precisely, the lack of a fourth line that affects questions in the same way.

The fact that you got 973 from the generator using questions, despite the size of questions_num being only 965, makes this a near certainty.

Perhaps it might be a good idea to keep them in sync.

Upvotes: 4

Neeraj Jain
Neeraj Jain

Reputation: 7730

Exception in thread "Thread-1" java.lang.IndexOutOfBoundsException:
Index: 973, Size 965

This exception is self explanatory . Size of questions_num is 965 and your are trying to access it outside the bounds i.e. 973

As JavaDocs says

IndexOutOfBoundsException is Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

Upvotes: 2

Related Questions