7

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?

Community
  • 1
  • 1
BrobaFett44
  • 101
  • 1
  • 1
  • 5
  • 4
    I think this will help: http://stackoverflow.com/questions/5950155/java-arrays-length – damiankolasa Nov 26 '12 at 06:55
  • + 1 fatfreddy, I was commenting with that link ;) You could determine most data type array (char, string, object, int) length using `Length` property of array object. – bonCodigo Nov 26 '12 at 07:06

4 Answers4

9

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);
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
vels4j
  • 11,208
  • 5
  • 38
  • 63
8

We only have .length but NOT .length(), regardless of the type of the array.

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
5

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.

Isaac
  • 16,458
  • 5
  • 57
  • 81
  • 1
    Array in Java is NOT immutable. It is just not resizable. Consider an array being a construct that holds multiple values/object-references, immutable will means once it is instantiated, we cannot change the values it is storing. However it is not the case. We can always do `myArray[2] = whatever;`. – Adrian Shum Mar 30 '15 at 04:53
  • @AdrianShum thank you, corrected wrong choice of words. – Isaac Mar 30 '15 at 07:19
  • Is the `myArray.length()` refers to how many items are in the array? – Ido Naveh Jul 21 '16 at 12:17
3

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?

Community
  • 1
  • 1
hyde
  • 60,639
  • 21
  • 115
  • 176