Arrays.copyOfRange(byte [],int,int)背后的逻辑是什么奇怪的行为?

Iva*_*met 9 java arrays standard-library

谁能解释一下Arrays.copyOfRange(byte [],int,int))奇怪行为背后的逻辑?我可以用简单的例子来说明我的意思:

byte[] bytes = new byte[] {1, 1, 1};
Arrays.copyOfRange(bytes, 3, 4); // Returns single element (0) array
Arrays.copyOfRange(bytes, 4, 5); // Throws ArrayIndexOutOfBoundsException
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,我都会复制数组边界之外的范围(即start >= array.length),因此错误的条件对我来说至少是奇怪的(如果from < 0from > original.length).在我看来应该是:如果from < 0from >= original.length.也许我错过了什么?

Mic*_*ael 5

JavaDoc指定了关于它期望的参数的三点:

一:

[ from ]必须位于original.length之间(含)

二:

[ to ]必须大于或等于from

三:

[ to ] 可能大于original.length

对于以下情况Arrays.copyOfRange(bytes, 3, 4)为真,这意味着它们是有效的。

对于只有两个和三个的情况,Arrays.copyOfRange(bytes, 4, 5)这意味着它们是无效的。


预期的行为?是的。

不直观的行为?有点。

如果你私底下的疑问是“为什么要这样设计?” 那么除了代码作者之外没有人能告诉你答案。


小智 0

看看 copyOfRange 是如何工作的:

public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
    int newLength = to - from;
    if (newLength < 0)
        throw new IllegalArgumentException(from + " > " + to);
    @SuppressWarnings("unchecked")
    T[] copy = ((Object)newType == (Object)Object[].class)
        ? (T[]) new Object[newLength]
        : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, from, copy, 0,
                     Math.min(original.length - from, newLength));
    return copy;
}
Run Code Online (Sandbox Code Playgroud)

最重要的部分是:

System.arraycopy(original, from, copy, 0,
                     Math.min(original.length - from, newLength));
Run Code Online (Sandbox Code Playgroud)

所以当你调用 Arrays.copyOfRange(bytes, 3, 4); 时 System.arraycopy 的最后一个参数“length - 要复制的数组元素的数量”为 0。 arraycopy 的调用如下所示: System.arraycopy(original, from, copy, 0,0);