KONADO
KONADO

Reputation: 189

ArrayList IndexOutOfBoundsException even though handled

I have a method which tries to get the current message in an arraylist of mesages and if there are none then it returns null, however I get an index out of bounds exception and I can't understand why

public Message getCurrent() {
    if(this.size() <= 0) {
        return null;
    }else {
        return this.get(currentMessageIndex);
    }

}

The following calls the above method in another class and throws the exception:

public void run() {
    while (running) {
        //Message msg = clientQueue.getLast(); // Matches EEEEE in ServerReceiver
        Message msg = clientQueue.getCurrent();
        System.out.flush();
        if (msg != null) {
            if (msg.getSent() == false) {
                client.println(msg);// Matches FFFFF in ClientReceiver
                client.flush();
                msg.setSent();

            }
        }
    }
    return;
}

Upvotes: 1

Views: 76

Answers (2)

VinodKumarReddy
VinodKumarReddy

Reputation: 77

public Message getCurrent() {
if(this.size() <= 0) {
    return null;
}else {
    return (this.size() > currentMessageIndex) ? this.get(currentMessageIndex) : null;
}}

Can you try with this, I have handled fail over case.

Upvotes: 1

tarun narain
tarun narain

Reputation: 72

Just use

this.size()-1 

Instead of

this.size()

Upvotes: 0

Related Questions