【问题标题】:Why do I get IndexOutOfBoundsException at index = -2147483648 (= Integer.MIN_VALUE)?为什么我在 index = -2147483648 (= Integer.MIN_VALUE) 处得到 IndexOutOfBoundsException?
【发布时间】:2017-04-21 06:05:03
【问题描述】:

以下代码将一直运行,直到抛出 IndexOutOfBoundExceptionstating h is -2147483648

一开始h=0它只会递增,不会递减。怎么会变成负数?

float[] powerArray = new float[8760];
int h = 0;
for (TShortIterator it = heightData.iterator(); it.hasNext();) {
    short wspeed = it.next();
    if (h < 8760) {                 
        powerArray[h] = Math.min(wspeed, 4);
    }
    h++;
}

【问题讨论】:

  • 用这样的基于范围的循环进行迭代有点奇怪
  • 这是一个质量很差的问题和答案。目前状态下,正确答案只是because array index has to be between 0 and the array length, and -2147483648 is not
  • 原来的代码不是我写的,但要自己处理。
  • @Jhamon:把它写成答案,我会接受的。 :) 这个问题的目的是在搜索 indexoutoufboundexception 和 -2147483648 时得到一个结果。

标签: java for-loop indexoutofboundsexception


【解决方案1】:

如果迭代器的条目多于Integer.MAX_VALUE,则会出现此问题。

h 递增,直到达到Integer.MAX_VALUE。在下一次递增时,整数溢出并变为Integer.MIN_VALUE=-2147483648

然后表达式 powerArray[-2147483648] 由于负索引而失败。

【讨论】:

  • 您是同时提问和回答的吗?如果你知道答案,为什么还要问?
  • @Aidin answering your own question 没什么问题。
  • @jesper 是的,我明白了。但他确实在他要求的同一分钟做到了
  • @Aidin Stack 允许这样做,如果你有一些不重复且有用的东西,那么你可以自己回答,但在这种情况下,因为没有关于 getHeightData(sensorHight) 做什么的代码,所以不太确定关于它
  • @Aidin 是的,那又怎样? SO 甚至还有一个特殊选项可以让你同时发布问题和答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 2014-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 2017-07-16
相关资源
最近更新 更多