有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组Java如何有效地检查ArrayIndexOutOfBounds?

Java使用什么机制来有效地检查我试图访问的数组元素是否超出范围。我认为它可以做到这一点的一种方法是在内存中的数组之前有元数据。但在每次检查时使用if语句在时间上效率很低。那么它实际上是如何做到的呢


共 (2) 个答案

  1. # 1 楼答案

    这是一段非常著名的代码,因为Oracle vs Google battle:

    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);
    
    }
    

    此方法在内部调用

  2. # 2 楼答案

    下面的简单检查就可以了

     int[] a = new int[2];
    
    if (a.size >= index )
     System.out.println("Item " + a[i]);