ArrayList IndexOutOfBoundsException 即使已处理

ArrayList IndexOutOfBoundsException even though handled

我有一个方法试图在消息数组列表中获取当前消息,如果有 none 那么它 returns 为空,但是我得到一个索引越界异常,我不明白为什么

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

}

下面在另一个class中调用上述方法并抛出异常:

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;
}

只需使用

this.size()-1 

而不是

this.size()
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.