# How do I let the user choose how big an array is...

• October 4th, 2010, 09:14 PM
Roon Hapoon
How do I let the user choose how big an array is...
...but that user doesn't know how big the array is going to be off the top of his head.

Let's say I have a for loop that takes user input (integers) and stores them into an array. But the loop doesn't exit until a negative number is typed. How would I do that to make sure I don't go out of bounds of the array, but I don't want a ton of extra values left over either? Because I'm going to sum these numbers once it's all done, and I don't want the 0 values effecting my sum.
• October 4th, 2010, 09:20 PM
copeg
Re: How do I let the user choose how big an array is...
ArrayList (Java Platform SE 6) gives you a dynamic array where an initial size isn't required.
• October 5th, 2010, 12:15 AM
helloworld922
Re: How do I let the user choose how big an array is...
The underlying implementation of Arraylists (and Vectors for that matter):

Create an array of some capacity. You will need 1 other variable to hold the actual number of elements in the array. Then, all you need to do is define a few operators:

1. Add - Adds an element to the end of the array. If the size of the array is equal to the current capacity, you need to allocate a larger array (generally 1.5x or 2x as large) and copy over all the items inside your old array. Increase size by 1.
2. Set - same as assigning an element in the array a value. You will need to check to make sure the index passed is less than size otherwise you're assigning an invalid location.
3. Remove - moves all emements behind the given index up by 1. decrease the size by 1.
4. Insert - Check to see if the current size is less than the capacity. If it is, move all elements behind the given index one space back and put the item into that spot. Increase the size. If it's not, allocate a new array (in the same process as described in add). Add all items from the original array up to the index. Add the new item. Add all the items after that index. Increase the size.