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

    Join Date
    Oct 2010
    Rep Power

    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
    Chicago, IL
    Rep Power
    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
    class Sig{public static void main(String...args){\u0066or(int

IMN logo majestic logo threadwatch logo seochat tools logo