Java String array: is there a size of method?

后端 未结 11 2019
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 03:38

I come from a php background and in php, there is an array_size() function which tells you how many elements in the array are used.

Is there a similar

11条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 04:11

    The answer is "All of them". A java array is allocated with a fixed number of element slots. The "length" attribute will tell you how many. That number is immutable for the life of the array. For a resizable equivalent, you need one of the java.util.List classes - where you can use the size() method to find out how many elements are in use.

    However, there's "In use" and then there's In Use. In an class object array, you can have element slots whose elements are null objects, so even though they count in the length attribute, but most people's definitions, they're not in use (YMMV, depending on the application). There's no builtin function for returning the null/non-null counts.

    List objects have yet another definition of "In Use". To avoid excessive creation/destruction of the underlying storage structures, there's typically some padding in these classes. It's used internally, but isn't counted in the returned size() method. And if you attempt to access those items without expanding the List (via the add methods), you'll get an illegal index exception.

    So for Lists, you can have "In Use" for non-null, committed elements, All committed elements (including null elements), or All elements, including the expansion space presently allocated.

提交回复
热议问题