We can determine the length of an ArrayList<E>
using its public method size()
, like
ArrayList<Integer> arr = new ArrayList(10);
int size = arr.size();
Similarly we can determine the length of an Array
object using the length
property
String[] str = new String[10];
int size = str.length;
Whereas the size()
method of ArrayList
is defined inside the ArrayList
class, where is this length
property of Array
defined?
it's public final field , which contains the number of components of the array (length may be positive or zero)
An array thus has the same public fields and methods as the following class:
more info at
10.7 Array Members
http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html
It's defined in the Java language specification:
Since there is a limitless number of array types (for every class there is a corresponding array type, and then there are multidimensional arrays), they cannot be implemented in a class file; the JVM has to do it on the fly.
To answer it as it-is, where is this length property of array defined? In a special
Object header
.Easy to see via JOL
One of the lines from this output is going to be:
Usually Objects have two headers (mark and klass), arrays have one more that always occupy
4 bytes
in length, assize
is anint
.The keyword length acts like a data filed defined. When using in an array, we can use it to access how many elements in an array. Regarding to String[], we can invoke length() method defined in String class. With regard to ArrayList, we can use size() method defined in ArrayList. Note that when creating an array list with ArrayList<>(capacity), the initial size() of this array list is zero since there is no element.
It's "special" basically, with its own bytecode instruction:
arraylength
. So this method:is compiled into bytecode like this:
So it's not accessed as if it were a normal field. Indeed, if you try to get it as if it were a normal field, like this, it fails:
So unfortunately, the JLS description of each array type having a public final field
length
is somewhat misleading :(Arrays are special objects in java, they have a simple attribute named
length
which isfinal
.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.
Resources: