Possible Duplicate:
Java Arrays - length
How do you determine the length of an array that is not an String array or an integer array? It won't let me use .length()
, but only .length
?
Why and is there another way of determining this?
Possible Duplicate:
Java Arrays - length
How do you determine the length of an array that is not an String array or an integer array? It won't let me use .length()
, but only .length
?
Why and is there another way of determining this?
You can use getLength
method from java.lang.reflect.Array
, which uses reflection (so it'll be slow):
Object[] anArray = new Object[2];
int length = Array.getLength(anArray);
We only have .length
but NOT .length()
, regardless of the type of the array.
Arrays in Java are not resizable. Once an array is instantiated, its length cannot change. That's why the length
attribute (myArray.length
) can always be trusted to contain the array's length.
Indeed, array length
is not a method. But you still use that to determine the length of an array.
Are you saying that myArray.length()
works for String
or int
/Integer
array?
Anyway, when using array in Java, always consider if using ArrayList
would suit your purpose better.
Edit: copying the useful SO link from comment of @fatfredyy to be in an answer: How is length implemented in Java Arrays?