Where is array's length property defined?
Arrays are special objects in java, they have a simple attribute named length
which is final
.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
10.7. Array Members
The members of an array type are all of the following:
- The
public
final
fieldlength
, which contains the number of components of the array.length
may be positive or zero.The
public
methodclone
, which overrides the method of the same name in classObject
and throws no checked exceptions. The return type of theclone
method of an array typeT[]
isT[]
.A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
- All the members inherited from class
Object
; the only method ofObject
that is not inherited is itsclone
method.
Resources:
- JLS - Arrays
How length property of an array works in javascript?
Array.prototype.length
is a writable property of array.
Adding description from Array#length
MDN
You can set the length property to truncate an array at any time. When you extend an array by changing its length property, the number of actual elements does not increase; for example, if you set length to 3 when it is currently 2, the array still contains only 2 elements. Thus, the length property does not necessarily indicate the number of defined values in the array.
This can be used to shorten an array.
As I understand, array in javascript is also an object:
console.log(typeof [1, 2, 3]); // object
Check Why does typeof array with objects return "Object" and not "Array"?
array length property in java
From Java Virtual Machine Specification. Chapter 3. Compiling for the Java Virtual Machine. 3.9 Arrays:
Java Virtual Machine arrays are also objects. Arrays are created and manipulated using a distinct set of instructions. The
newarray
instruction is used to create an array of a numeric type. The code:void createBuffer() {
int buffer[];
int bufsz = 100;
int value = 12;
buffer = new int[bufsz];
buffer[10] = value;
value = buffer[11];
}
might be compiled to:
Method void createBuffer()
0 bipush 100 // Push int constant 100 (bufsz)
2 istore_2 // Store bufsz in local variable 2
3 bipush 12 // Push int constant 12 (value)
5 istore_3 // Store value in local variable 3
6 iload_2 // Push bufsz...
//line below is what you're looking for [comment is mine]
7 newarray int // ...and create new int array of that length
9 astore_1 // Store new array in buffer
10 aload_1 // Push buffer
11 bipush 10 // Push int constant 10
13 iload_3 // Push value
14 iastore // Store value at buffer[10]
15 aload_1 // Push buffer
16 bipush 11 // Push int constant 11
18 iaload // Push value at buffer[11]...
19 istore_3 // ...and store it in value
20 return
The newarray int
instruction initializes the array and its length. Which means that the array length is initialized when you initialize the array, at runtime.
The explanation from link above also explains how an array of references is created by the anewarray
instruction, and shows a similar pattern.
Use Array.length property and not a function to return length of an array by counting only distinct elements and not all elements
This is barely possible, but it's really weird. If you create another object that wraps the array, you can make the length
property a getter that deduplicates items and returns the size, something along the lines of:
const makeSpecialArr = (arr) => {
const specialArr = Object.create(arr);
Object.defineProperty(specialArr, 'length', {
get() {
return new Set(arr).size;
},
});
return specialArr;
};
const arr = makeSpecialArr([2, 2, 5, 3, 5, 3, 4, 7, 2, 7]);
console.log(arr.length);
length property of Array.prototype object - ES 5
MDN says:
Array.prototype.length
reflects the number of elements in an array.
Is it a right definition?
Sorta, yes. There are three different .length
properties related to arrays:
Array.length
. As you said, it's an instance ("own") property that all functions have, and has nothing to do with arrays specifically.arr.length
, wherearr
is an array instance (e.g.arr = ['ex', 'ample']
). Every array has this special property that acts a bit like a getter/setter, automatically determining the highest array index property that the object has.Array.prototype.length
is a special case of #2, asArray.prototype
is just an array object itself - empty by default, therefore.length == 0
.
MDN is a bit inaccurate because it mixes instance properties with those inherited from the prototype in its documentation pages. As your diagram correctly visualises, all of the cars
, bikes
and Array.prototype
objects do have their own .length
property with its own value (and changing one doesn't change the others of course).
So what purpose does Array.prototype.length
have? Not much, actually, as it's typically shadowed by an own property of the array objects that inherit from Array.prototype
. So apart from just being there because the spec says that Array.prototype
is an array instance and those have that property, it can also serve as a sensible default .length
value on normal (non-array) objects that inherit from Array.prototype
- those cases are very rare though.
Why is length a property of `Array` not `Array.prototype` chain
That is not a bug. By definition, Object.getOwnPropertyNames
will return all the enumerable and non-enumerable own properties of an object. When it comes to an array, length is an own property but its enumerable property is false. That's the reason why it is getting included in the result.
you can test it with the following snippet,
console.log(Object.getOwnPropertyDescriptors([]));
The above code will return the descriptors of all the own properties. Inspect it, you will get to know about its enumerable property.
Is the JavaScript Array.length property a function or a simple variable?
It is a property that gets increased or decreased as you push elements to the array object.
For example my (fake) object:
var myArray = function(){
this.length = 0;
this.push = function(itm){
this.length++;
// ^ doesn't do anything aside from increase length
};
};
what mean .length property in an array variable
.length
returns the number of elements in the array. That's how many items you need to iterate over in your for
loop when looking at all of them.
Related Topics
Removing an Element from an Array (Java)
Can You Recommend a Java Library for Reading (And Possibly Writing) CSV Files
Can't Add Value to the Java Collection with Wildcard Generic Type
How to Wire One Pane to Another
Java Comparison with == of Two Strings Is False
How to Switch Between Frames in Selenium Webdriver Using Java
Why Doesn't Java Send the Client Certificate During Ssl Handshake
Do I Need <Class> Elements in Persistence.Xml
Multiple Returns: Which One Sets the Final Return Value
How to Map Calculated Properties with JPA and Hibernate
How to Avoid "Staleelementreferenceexception" in Selenium
Why Does Writeobject Throw Java.Io.Notserializableexception and How to Fix It
Java "Void" and "Non Void" Constructor
Regex to Match a C-Style Multiline Comment