有 Java 编程相关的问题?

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

数组。java中的copyOfRange方法引发不正确的异常

我今天正在处理数组,突然遇到了一个抛出意外异常的场景

如果您查看下面的代码,我认为它必须抛出ArrayIndexOutOfBoundsException,但令人惊讶的是,它反而抛出了IllegalArgumentException

import java.util.Arrays;
public class RangeTest {
public static void main(String[] args) {
    int[] a = new int[] {0,1,2,3,4,5,6,7,8,9};
    int[] b = Arrays.copyOfRange(a, Integer.MIN_VALUE, 10);
    // If we'll use Integer.MIN_VALUE+100 instead Integer.MIN_VALUE,
    // OutOfMemoryError will be thrown
    for (int k = 0; k < b.length; k++)
        System.out.print(b[k] + " ");
   }
}

如果我错了,谁能帮我一个忙,让我知道吗


共 (4) 个答案

  1. # 1 楼答案

    您将面临最小值=-2147483648[0x8000000]的错误,该值为负。u设置为0,即Arrays.copyOfRange(a, 0, 10);。它将允许你复制

  2. # 2 楼答案

    你发送整数。最小值(-2147483648)作为起始范围。 您可能打算改为发送0

  3. # 3 楼答案

    java文档和实现之间存在不匹配

    正如Eran所解释的,由于int溢出,我们得到了一个IllegalArgumentException异常,而不是ArrayIndexOutOfBoundsException异常

  4. # 4 楼答案

    好吧,Javadoc说:

    Throws:

    • ArrayIndexOutOfBoundsException - if from < 0 or from > original.length

    • IllegalArgumentException - if from > to

    查看实现,您可以看到由于int溢出,您得到了一个IllegalArgumentException异常,而不是ArrayIndexOutOfBoundsException

    public static int[] copyOfRange(int[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        int[] copy = new int[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }
    

    此代码认为from>to因为to-from导致int溢出(因为fromInteger.MIN_VALUE),这导致了负newLength