Home > Net >  Getting the size of a generic array? (not the length) [closed]
Getting the size of a generic array? (not the length) [closed]

Time:09-27

I have created a generic array called "data". I can use data.length to get its capacity, however when I try to return its logical size, using data.size() returns the error: Cannot invoke size() on the array type T[]. To get its size, would I need to make a loop and count the elements one by one or is there a better method of returning the number of filled spaces in a generic array?

Also if you have the time, would the elements in the generic array be considered objects as opposed to primitive types (for example, Integer instead of int)? Any help would be appreciated!

CodePudding user response:

Arrays in Java don’t have any concept of a logical size. They are a low-level construct with a fixed length. In most cases, it is preferable to use java.util.ArrayList or another class from the Collections Framework.

ArrayList implements its size() method by encapsulating an array and keeping a separate field that counts the number of items added to it. This avoids any need to iterate the array to return the logical size.

  • Related