permaculture playing cards*
The moose likes Beginning Java and the fly likes # of items in an array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "# of items in an array" Watch "# of items in an array" New topic
Author

# of items in an array

Patty Kingsmill
Greenhorn

Joined: Nov 20, 2005
Posts: 7
How do I count the the number of items in an array? I have an array with an index of 15, i.e.,

collection [15]

But suppose I only fill 5 of those 15 slots with data. How do I get a count of how many slots are filled? Is there an expression like collection.length?

Thanks (and grateful I've found this forum)
Patty
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

I don't know of any methods in the API for this, so I think you need to write your own method that iterates through the array checking for null references (if the array holds object references) or zeros (if it holds primitives).


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Patty Kingsmill
Greenhorn

Joined: Nov 20, 2005
Posts: 7
I was afraid of that.

Thanks
Patty
Chad Clites
Ranch Hand

Joined: Aug 16, 2005
Posts: 134
It's not hard. All you need is a single int that is initially set to zero. Every time something gets added to the array, then increment the count. When something is removed, decrement the count. Then the only thing one needs to remember is that when the Array has one thing in it, it is actually at index 0, and your count index will be one.
[ November 26, 2005: Message edited by: C Clites ]
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Note: If the array holds object references, then checking for null is probably okay. But if the array holds primitive values, then you need to be careful to define what "no item" really means, because the default initialization of zero (or false) might be a perfectly valid assignment.
 
jQuery in Action, 2nd edition
 
subject: # of items in an array