arrayList = [‘One’, ‘Two’, ‘Three’, ‘Four’, ‘Five’]
arrayList.length is 5
When I do
arrayList.length , what is the action behind the scene ?
- arrayList is iterated and length is returned
- length is pre-calculated at Data Structure being used for Array
array.length is an attribute. It is not “computed” each time by counting elements.
Note that when you assign a new value to an array’s length attribute, the runtime system will take care of growing or shrinking the array for you.
I would like to know about an in general behavior across various languages.
You can’t generalize:
Some languages allow you to change the size of an array; for example Python, Ruby, and so on. This is not necessarily done by assigning to a length or size attribute.
In Python for example, the length of an array (or a list) is not an attribute. It is the value returned by the
lenfunction. You change a Python array size by adding and removing elements.
In Ruby, the length of an array is a read-only attribute.
Other languages do not allow the length on a primitive array to be changed; for example Java, Ada and so on.
And for some languages (C, BCPL) an array’s length is not part of its runtime value. (Indeed, in BCPL arrays are not even a type.) So that means that an application can’t access the array’s length. It has to be handled as a separate variable, or deduced via (say) a zero termination convention. (The latter implies that you compute the array’s notional length by iteration, but you need to worry about overrun.)