#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2010
    Posts
    66
    Rep Power
    9

    How do I make an array with an unknown number of elements?


    I am supposed to read from a file and store in an array ( not array list ). The number of lines in the file is unknown, so i need to make an array with an unknown amount of elements, How could I do that?
  2. #2
  3. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    Chicago, IL
    Posts
    10,131
    Rep Power
    5058
    1. Why can you not use ArrayList (or other implementation of a list)? Is that a requirement of a homework assignment?

    2. If you absolutely must use an array, then you have a couple options:

    2a. Read through the file once to determine the number of "lines", allocate the array using that number, then read through the file again to populate the array.

    2b. Take a guess at the size of the file, allocate the array, and start reading lines into the array. If the array is not large enough, then resize the array (e.g., System.arraycopy()) with another reasonable guess. In effect, you'll be mimicking the behavior of ArrayList.

    Hope this helps!

    ~

    Comments on this post

    • mvantuyl agrees
    • sunvsunv agrees
    • codeJ agrees
    Yawmark
    class Sig{public static void main(String...args){\u0066or(int
    \u0020$:"v\"ʲ\"vΤ\"".to\u0043h\u0061rArray()
    )System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
    +(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}

IMN logo majestic logo threadwatch logo seochat tools logo