CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: array problem

  1. #1
    Join Date
    May 2009
    Posts
    9

    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

  2. #2
    Join Date
    Apr 2007
    Posts
    442

    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.

  3. #3
    Join Date
    May 2009
    Posts
    9

    Re: array problem

    ah thanks didn't know about the fixed size

  4. #4
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    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 &#91;CODE]...your code here...&#91;/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
  •  





Click Here to Expand Forum to Full Width

Featured