【问题标题】:ArrayList IndexOutOfBoundsException even though handledArrayList IndexOutOfBoundsException 即使已处理
【发布时间】:2018-07-24 03:20:54
【问题描述】:

我有一个方法试图在消息数组列表中获取当前消息,如果没有,则返回 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;
}

【问题讨论】:

  • 你在扩展一个 ArrayList 吗?如果是这样,我认为您真的应该质疑为什么需要这样做...
  • 看起来您在多线程环境中运行它。你把它称为 this.size 是什么意思?
  • 在哪里处理,错误信息在哪里?
  • @notionquest消息数组列表的大小
  • 看起来您在多线程环境中运行它。除非您在添加/删除和从中获取消息时向我们展示您是如何使用 clientQueue 的,否则您只会得到推测性的答案。

标签: java arraylist exception-handling indexoutofboundsexception


【解决方案1】:

随便用

this.size()-1 

代替

this.size()

【讨论】:

  • 这将如何帮助避免 OP 出现的错误?
  • 使用 if(this.size!=0)
  • 当前if(this.size() &lt;= 0) 检查将处理空大小。虽然检查负大小是没有意义的,但是代码仍然有效。
【解决方案2】:
public Message getCurrent() {
if(this.size() <= 0) {
    return null;
}else {
    return (this.size() > currentMessageIndex) ? this.get(currentMessageIndex) : null;
}}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-15
    • 2016-03-22
    • 2014-01-14
    • 2015-11-07
    • 2013-11-06
    • 2016-11-07
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多