Search code examples
javaarraysstringtemporary-filestemporary-objects

How to store sentences in a temporary array in Java?


Currently, I am scraping out a chunk of data (paragraphs/strings) from a text file and writing it out to a new file. However, I am planning on adding some conditionals later and thus want to be able to take out this chunk of data and only store it in a temporary array, then write out to a file if the conditionals are met. However, I am not sure how to write this out to an array without knowing the size of the array beforehand.

Does anyone have any ideas?


Solution

  • Don't use an array. Use a collection of type String that can grow dynamically such as an ArrayList for example. Here are some quick code samples: Sample 1, Sample 2

    Some notes on an ArrayList's memory management from the Java docs:

    The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

    An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

    Notice that even the docs do not specify exactly how things are managed internally.