I was wondering about the implementation of length
of a Java Array. I know that using arrayName.length
gives us the number of elements in the array, but was wondering if this is a method / function or it is just a data member of Array?
I guess it must be a data member as we do not use parenthesis()
when invoking it. But if it is a data member how/when is the value of this length
assigned/computed?
Yes, it should be a field. And I think this value is assigned when you create your array (you have to choose the length of array while creating, for example: int[] a = new int[5];
).
You're correct, length
is a data member, not a method.
From the Arrays tutorial:
The length of an array is established when the array is created. After creation, its length is fixed.
If you have an array of a known type or is a subclass of Object[] you can cast the array first.
Object array = new ????[n];
Object[] array2 = (Object[]) array;
System.out.println(array2.length);
or
Object array = new char[n];
char[] array2 = (char[]) array;
System.out.println(array2.length);
However if you have no idea what type of array it is you can use Array.getLength(Object);
System.out.println(Array.getLength(new boolean[4]);
System.out.println(Array.getLength(new int[5]);
System.out.println(Array.getLength(new String[6]);
Java arrays, like C++ arrays, have the fixed length that after initializing it, you cannot change it. But, like class template vector - vector <T>
- in C++ you can use Java class ArrayList
that has many more utilities than Java arrays have.
I believe its just a property as you access it as a property.
String[] s = new String[]{"abc","def","ghi"}
System.out.println(s.length)
returns 3
if it was a method then you would call s.length()
right?
It is a public final
field for the array type. You can refer to the document below:
http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.7
Every array in java is considered as an object. The public final length
is the data member
which contains the number of components of the array (length
may be positive or zero)
From the JLS:
The array's length is available as a final instance variable length
And:
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.
And arrays are implemented in the JVM. You may want to look at the VM Spec for more info.
Source: Stackoverflow.com