【问题标题】:Index 1, size 1 Exception索引 1,大小 1 例外
【发布时间】:2016-06-15 10:27:50
【问题描述】:

我查看了有关此异常的所有问题。我知道数组索引从0开始,如果大小为1,我们只能访问索引0。虽然我知道这个逻辑,但我无法修复以下代码。

  private static Map<String, Map<String, List<String>>> executions = new HashMap<String, Map<String, List<String>>>();

public static String readExecution(String jobName, String deviceName, int executionNumber) {
    String result = null;
    Map<String, List<String>> jobExecutions = executions.get(jobName);
    if (jobExecutions != null) {
      List<String> executionPerDevice = jobExecutions.get(deviceName);
      result = executionPerDevice.get(executionNumber); // ERROR
    }

    return result;
  }

编辑: Fildor的comment.execution number的答案是1。

有什么帮助吗? 谢谢。

【问题讨论】:

  • 调试它。我会说executionNumber 是“1”。如果您从 1 开始对执行进行编号,则将其设为 result = executionPerDevice.get(executionNumber-1); 我还会进行一些空值检查。
  • 你能检查 executionPerDevice 的大小并将其与 executionNumber 进行比较吗?
  • IndexOutOfBound 异常是一个非常简单的异常。你试图得到一些不存在的东西。只需调试您的代码,找出为什么在获取它时没有价值。
  • 如果deviceName 不在jobExecutions 中会怎样? (反问)
  • 你有它。因此,您实际上是在尝试在其大小为 1 时执行 executionPerDevice.get(1)。您已经说过您知道这是错误的。索引应为 0。请参阅我的第一条评论。

标签: java indexoutofboundsexception


【解决方案1】:

快速解决方案: 执行编号作为参数从外部传递,因此您应该检查此编号是否符合 executionPerDevice 大小:

      if (executionPerDevice.size() >= executionNumber){
            result = executionPerDevice.get(executionNumber);
        }

【讨论】:

  • @NicolasFilotto 我还是新手,你能解释一下为什么你认为这个条件是错误的
  • 因为 List 中的索引从 0 变为包含大小 -1,所以这里的测试不正确,因为您可能有 executionNumber == size 这会导致 IndexOutOfBoundsException
【解决方案2】:

这些运行时异常消息往往会告诉您一切您需要了解以了解问题。

大小为一

索引为 ONE。

考虑大小为 1 的列表的有效索引集。

【讨论】:

    猜你喜欢
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多