Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

adding to an existing array

 
tan kian
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 64629
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.util.ArrayList is perfect for this purpose.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
tan kian
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the advice everyone. i will try the arraycopy methods and ask again if i have any problems.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic