问题
I was working on arrays today and suddenly I came across a scenario throwing unexpected exceptions.
If you look at the code below , I think it must throw ArrayIndexOutOfBoundsException
, but surprisingly it is throwing IllegalArgumentException
instead:
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] + " ");
}
}
Can anybody help me and let me know if I am mistaken?
回答1:
Well, the Javadoc says :
Throws:
ArrayIndexOutOfBoundsException - if from < 0 or from > original.length
IllegalArgumentException - if from > to
Looking at the implementation, you can see that you got an IllegalArgumentException
exception instead of ArrayIndexOutOfBoundsException
due to int
overflow :
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;
}
This code thinks that from
> to
because to-from
caused int overflow (due to from
being Integer.MIN_VALUE
), which resulted in a negative newLength
.
回答2:
You send Integer.MIN_VALUE(-2147483648) as from range. You probably meant to send 0 instead
回答3:
You face error as MIN_VALUE = -2147483648 [0x80000000] which is negative. either u set 0 i.e. Arrays.copyOfRange(a, 0, 10);
. it will allowed you to copy.
回答4:
There is miss match between java Docs and implementation
As expalained by Eran we can see that we got an IllegalArgumentException exception instead of ArrayIndexOutOfBoundsException due to int overflow .
来源:https://stackoverflow.com/questions/34507935/arrays-copyofrange-method-in-java-throws-incorrect-exception