1

我有一个 ArrayIndexOutOfBoundsException

private Size getPictureSize() {
    List<Size> list = camera.getParameters().getSupportedPictureSizes();
        int i = 0;
    for (Size size : list) {
        if (Math.min(size.width, size.height) <= 800) {
            if (Math.max(size.width, size.height) > 800) {
                return size;
            } else {

                return (i > 0 ? list.get(i - 1) : list.get(0));
            }
        }
        i++;

    }

    return list.get(0);
}

这是有人在将其投放市场后要求我测试的应用程序的一部分,其中一个错误报告是在线的

return (i > 0 ? list.get(i - 1) : list.get(0));

我知道这个异常意味着什么,但是什么可能导致它?

4

1 回答 1

1

您的代码中有几个问题:

  • 这一行:return (i > 0 ? list.get(i - 1) : list.get(0));可能会计算一个在您的列表中不存在的索引;
  • 如果您的列表为空,则代码的最后一行 ( return list.get(0);) 可能会引发一个。IndexOutOfBoundsException

我更改了您的代码以解决这些问题。看看能不能解决你的问题:

private Size getPictureSize() {
    List<Size> list = camera.getParameters().getSupportedPictureSizes();
    Size prevSize = null;
    for (Size size : list) {
        if (Math.min(size.width, size.height) <= 800) {
            if (Math.max(size.width, size.height) > 800) {
                return size;
            } else {
                return (prevSize == null? size : prevSize);
            }
        }
        prevSize = size;
    }

    if(list.size() > 0) {
        return list.get(0);
    }

    return null;
} 
于 2012-04-09T14:45:29.580 回答