It's not a secret anymore!
The moose likes Beginning Java and the fly likes adding to an existing array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "adding to an existing array" Watch "adding to an existing array" New topic

adding to an existing array

tan kian
Ranch Hand

Joined: Apr 09, 2004
Posts: 40
hi all, what i'm trying to do here is to let the user create an array depending on the number he/she inputs, then add new records to it. for eg: 1st time user creates 2 accounts, then user adds 1 more account so total number of accounts will become 3.

i know i cant use the .length property that way, but its there to give u guys an idea what i'm trying to do, cause i cant think of any way to add to the existing array -_- thanks.
[ edited to surround code with the [code] and [/code] UBB Tags in order to help preserve formatting -ds ]
[ April 24, 2004: Message edited by: Dirk Schreckmann ]
Elouise Kivineva
Ranch Hand

Joined: Feb 07, 2002
Posts: 154
You have to specify the size of the array when you create it, you can't add to the length of an already-existing array.
You could
(1)use a more advanced structure, such as a vector or linked list to hold your accounts. These have flexible lenths.
OR (2)demand that the user tell you immediately how many accounts he wishes to create and store that many accounts. Do not attempt to store more or you will get an array out of bounds error.
OR (3) If you wish to use an array and create the illusion of flexible length, you could create an array larger than you could possibly need and then use a variable to keep track of how many of the array's indexes are in use (something like an int called "nextInsertIndex". If you don't allow deletions, nextInsertIndex would be equal to the number of accounts stored in the array).
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63866

java.util.ArrayList is perfect for this purpose.

[Asking smart questions] [About Bear] [Books by Bear]
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
If you wanted to use an array, when the existing array is full, you could create a new array of a larger size, copy all of the elements from the smaller, full array into the new, larger array, change your reference to the smaller array to refer to the larger array, and continue.
Note that for copying the components from one array to another, the arraycopy method in the System class is handy.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
tan kian
Ranch Hand

Joined: Apr 09, 2004
Posts: 40
thanks for the advice everyone. i will try the arraycopy methods and ask again if i have any problems.
I agree. Here's the link:
subject: adding to an existing array
It's not a secret anymore!