The unknown size of array

In Java, I am trying to read files and then I want to put them in an array. But when I declare an array, an error occurs because of unknown length. Here's an example:

Object unsortedInt[];
        try {
            BufferedReader bR = new BufferedReader(new FileReader(x));
            String values = bR.readLine();
            int index=0;
            while (values != null){
                unsortedInt[index]=values;
                values= bR.readLine();
                index++;
            }
            bR.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }

I can work with arraylist for this problem but is there a way that works with arrays ?

Jon Skeet
people
quotationmark

I can work with arraylist for this problem but is there a way that works with arrays ?

Only by reproducing the logic of ArrayList, basically. No, there's no way of getting a variable-length array. Arrays in Java just don't support that.

If you need an array later, you could create an ArrayList and then call toArray to create the array afterwards.

You could read the file once just to count the lines and then again to actually read the data... but it would be much better just to use an ArrayList while you read.

people

See more on this question at Stackoverflow