ArrayList IndexOutOfBoundsException即使已处理

时间:2018-02-13 17:13:45

标签: java arraylist exception-handling indexoutofboundsexception

我有一个方法试图在一个mesra的arraylist中获取当前消息,如果没有,那么它返回null,但是我得到一个超出范围的索引异常,我无法理解为什么

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

}

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

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

2 个答案:

答案 0 :(得分:1)

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

你可以试试这个,我已经处理了故障转移案例。

答案 1 :(得分:0)

只需使用

this.size()-1 

而不是

this.size()
相关问题