|
-
May 13th, 2009, 02:03 PM
#1
array problem
dear,
**** ashamed to ask this
i have a problem to with arrays in java.
it's an array of strings and i want to add another string to the end.
(it's in a try-catch statement, don't know if that changes enything)
MyArray[nexti] = MyString; doens't seem to work...
i tried using a list: MyList.add(MyString); not working...
big thanks wieweet
-
May 13th, 2009, 02:16 PM
#2
Re: array problem
Arrays are always of fixed size, so if you want to add something to an array you can create a new array that is one index larger, copy existing values to that array and then assign the value at the last index.
Code:
//assuming myArray is the array you want to add to, toAdd is the string added
String[] temp = new String[myArray.length+1];
for(int i=0;i<myArray.length;i++)temp[i]=myArray[i];
temp[temp.length-1]=toAdd;
myArray=temp;
Alternatively you can use utility methods in classes Arrays and Collections.
-
May 13th, 2009, 02:36 PM
#3
Re: array problem
ah thanks didn't know about the fixed size
-
May 13th, 2009, 04:59 PM
#4
Re: array problem
As Londbrok says, if you don't know in advance how many items you'll need to store, or the number of items can vary, use a collection class such as ArrayList.
Awaken people's curiosity. It is enough to open minds, do not overload them. Put there just a spark...
A. France
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|