Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

# of items in an array

 
Patty Kingsmill
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Patty Kingsmill
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was afraid of that.

Thanks
Patty
 
Chad Clites
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic