Re: Array Question

From: Anthony Borla (ajborla_at_bigpond.com)
Date: 12/22/03


Date: Mon, 22 Dec 2003 00:10:04 GMT


"Andrew Dixon - Depictions.net" <andrew.dixon@NOREPLY.depictions.net> wrote
in message news:%VjFb.2724$8x3.24779027@news-text.cableinet.net...
> Hi Everyone.
>
> Bit new to Java and I have question about arrays. I have wrote
> some code to look for certain substrings within a larger string
> which work fine. I would like to store each substring in an array,
> however I don't know how many there will be. All the example I
> have found for arrays only show how to predefine the size of the
> array, however I would like to expand it by one each time I need to.
> Can anyone let me know how to do this.
>

Sorry, no can do: arrays are fixed-size objects. In order to have a
'growable' or 'resizable' array you:

* Allocate a new, larger array, copy all elements from old array
   to the new array; this, effectively, disposes of the old array

   Pretty cumbersome approach - not recommended

* Use a Collection-based object for storage, and only create
   an array from this when needed [assuming you *must*
   have an array with which to work]. You might use an
   'ArrayList' or a 'Vector'. Quick example:

        String[] getArrayOfSubstrings(String bigString)
       {
           ArrayList list = new ArrayList();
           ...
           for (...)
           {
               ...
               list.add(bigString.substring(...));
               ...
           }
           ...
           return ((String[]) list.toArray(new String[list.size()]));
       }

I hope this helps.

Anthony Borla



Relevant Pages