I was wondering, why doesn't the java-compiler warn
for incorrect initializing of arrays, for example :
int[] myArray = new int[2];
myArray[3] = 1; // Runtime-error : ArrayIndexOutOfBoundsException.
Isn't it very easy for the compiler to detect this
kind of invalid code ?
Not if a separate thread is monitoring the array for null,
and, when not null - filling the values to the assigned
length.
?? You mean, the compiler cannot easily detect this kind
of invalid code because it uses an separate thread to
monitor the array for null and eventualy prefilling the
array ?
Is this just your gues or do you know for a fact that
this is the reason ?
I don't think that's what Andrew meant. Rather, he's saying that this
isn't a compile-time error because the int[] doesn't have a size, and it's
conceivable that your new int[2] could get 'externally changed' at
runtime, before the access to myArray[3] is run. I'm not sure how at risk
your example would be (since another thread doesn't have any reference to
it), and yes it would be pretty easy for the compiler to pick up, but it
doesn't take that many more statements to totally remove that.
I could see logic in your argument if we could do something like:
int[3] threeInts = new int[3];
error = threeInts[4];
but we can't (and don't need to) - an int[] variable holds 'an array of
ints', so the compiler cannot reliably (and so won't ever) infer the size
of an array in the way you suggest. Indeed, there's no way to know whether
a given array can return a given index at runtime until you ask the array
itself, since all arrays of a given element type and the same number of
dimensions are implemented by the same class.