-
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
-
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.
-
Re: array problem
ah thanks didn't know about the fixed size
-
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