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 < 0
或from > original.length
).在我看来应该是:如果from < 0
或from >= original.length
.也许我错过了什么?
小智 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);
归档时间: |
|
查看次数: |
583 次 |
最近记录: |