Since most other classes seem to let the developer retrieve the length or size of its content by calling a method, usually length()
or size()
, how come the length of an array is retrieved by reading the instance variable length
? It just seems inconsistent to me, especially since a String object is immutable as well and still uses a length()
method.
It is inconsistent. I suppose the actual reason for the distinction can only be found in the early history of Java language development. Perhaps it was for what seemed at the time to be performance reasons. I suspect that if Java were being (re)designed from scratch today, the length
field would disappear and instead there would be a java.lang.Array
class* (similar to java.lang.Enum
) from which all arrays would derive and which would include a length()
method inherited by all arrays.
Actually, the lack of an Array
class (in the above sense) may indicate why there's a length
attribute: arrays are more "built in" to the language than, say, the collection classes (which are part of a class library).
* Java does have java.lang.reflect.Array
, but that does something completely different from what I'm talking about.
Most of the collections have dynamic sizes, so they need a method to verify the length/size in that specific time. An array has a fixed length, so it doesn't need to be recalculated all the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With