The former (.length) isn't even a function , how does it return length?
1 Answers
The reason length
isn't function in an array is that it is a field. In particular, a public final
one as specified by the Java Language Specification section 10.7.
While ArrayList (ad Vector of the 1.0 libraries) have a length()
method, the key thing to realize is that this value can change. You call add(Object o)
on a Vector, and you've changed its length.
On the other hand, you can't change the length of an array.
Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.
(from JLS Section 10.2 - Array Variables)
And thus, the simplest thing that works is to make the length a field. One that is public and can't change.
Realize in the Java 1.0 days, HotSpot wasn't quite as advanced as it is today. It wouldn't be able to do all the optimizations that it can now with inlining methods. And thus, to make array access that much faster for situations that needed it, its a field.
Related reading on Stack Overflow: length and length() in java

- 1
- 1