DRAFT
ArrayLengthPartOfType
Misconception:
The type of an array is determined by the type of the elements
and by the length of the array
(e.g., int[3]
is the type of an integer array of length 3).
Incorrect
The length of an array is part of its type
Correct
The length of an array is not part of its type
CorrectionHere is what's right.
Here is what's right.
The type of an array does not depend on the array’s length. Two array objects with different lengths can have the same type. E.g.:
int[] a = new int[5];
int[] b = new int[9];
The types of a
and b
are identical.
They are int[]
(note: the type does not specify a length).
This makes it possible to assign an array of any length to a variable:
int[] a;
a = new int[5];
a = new int[9]; // this is perfectly fine!
It also means one has no static (compile-time) guarantee about the length of an array:
void plot(int[] start, int[] end) {
// Here, we don't have any guarantee
// that start and end are 2-d points,
// i.e., that they are arrays of length 2.
if (start.length!=2 || end.length!=2) {
// we need to handle the error at runtime
}
// work
}
Language
Java