You should use a List
for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List
instead. Most would probably tackle this problem by using an ArrayList
.
If you really can't use a List
, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList
does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList
.