Main Content

Length, size or capacity in Java?

Archive - Originally posted on "The Horse's Mouth" - 2010-02-24 18:45:44 - Graham Ellis

You get the length of an array, but you ask about the size() of an ArrayList, and you can inquire into the capacity() of a StringBuffer. Aren't they really all the same sort of thing? Which does Java use in which circumstance?

Java uses the word length when you're asking about something that can be determined by telling you the distance from the start to the end of something - thus an array, with fixed size elements arranged sequentially in memory, is going to be a length.

Java uses size where you're looking at a measure of the number of elements in something which is not in successive memory locations, or may not be, or where the elements themselves differ in size so you can't find out how many of them there are by measuring the distance from start to end.

And Java uses capacity where you're being told how much something can hold, and not how much it's holding at the moment.

Do you add brackets after the length / capacity / size word? If you're looking at a variable within the object, you don't, but if you're calling a method you do. Which is it in which circumstances? I have no magic answer - you just need to learn / know.




myarray.length - array length - [example]

MyArrayList.size() - number of elements in an Array List - [example]

MyString.length() - String length - [example]

MyStringBuffer.length() - String Buffer length - [example]

MyFile.length() - Number of bytes in a file - [example]

MyVector.size() - Number of elements in a Vector [example] and [example in Servlet]

MyAppletDimension.size() - returns an object with the width and height of an applet. This is deprecated and you should now use getsize ...

MyAppletDimension.getsize() - returns an object with the width and height of an applet - [example]

MyStringBuffer.capacity() - the number of characters that a StringBuffer can currently hold