-1

Java 使用什么机制来有效地检查我尝试访问的数组元素是否越界。我认为可以做到的一种方法是在内存中的数组之前放置元数据。但是每次检查时的 if 语句在时间上是非常低效的。那么它实际上是如何做到的呢?

4

3 回答 3

2

由于Oracle 与 Google 之战,这是一段非常有名的代码:

private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
    if (fromIndex > toIndex)

        throw new IllegalArgumentException("fromIndex(" + fromIndex +
                   ") > toIndex(" + toIndex+")");

    if (fromIndex < 0)
        throw new ArrayIndexOutOfBoundsException(fromIndex);

    if (toIndex > arrayLen)
        throw new ArrayIndexOutOfBoundsException(toIndex);

}

此方法在内部调用。

于 2012-12-17T08:15:37.910 回答
0

如下简单检查就可以了,

 int[] a = new int[2];

if (a.size >= index )
 System.out.println("Item " + a[i]);
于 2012-12-17T08:16:27.797 回答
0

如 JVM 7 规范中所述,它似乎确实检查了每个*aload, etc. 指令的边界。*astore

如果 index 不在 arrayref 引用的数组的范围内,则 (*astore,*aload,etc) 指令将引发 ArrayIndexOutOfBoundsException

但它的实际完成方式是特定于实现的。

于 2012-12-17T08:25:06.787 回答