数组大小未知

The unknown size of array

在Java中,我正在尝试读取文件,然后我想将它们放入一个数组中。但是当我声明一个数组时,由于未知长度而发生错误。这是一个例子:

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();
        }

我可以使用 arraylist 来解决这个问题,但是有没有一种方法可以处理数组?

为了使用数组,您必须将数组初始化为某个初始长度。如果当前数组对于您的输入来说太小,您可以稍后创建一个更大的数组(并将原始数组的内容复制到其中)。这就是 ArrayList 的实现方式。

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

只有重现ArrayList的逻辑,基本上。不,没有办法获得可变长度数组。 Java 中的数组不支持。

如果您稍后需要一个数组,您可以创建一个 ArrayList,然后调用 toArray 来创建数组。

可以读取文件一次只是为了计算行数,然后再读取一次以实际读取数据...但这将是很多 最好在阅读时使用 ArrayList

您可以尝试如下操作:

public class AddItemToArray {

    private int[] list = new int[0];//you should initialize your array first. 

    public int[] getList() {
        return list;
    }

    public void push(int i) {
        int fLen = list.length;//you can check the current length of your array and add your value to the next element of your array with the copy of previous array
        list = Arrays.copyOf(list, list.length + 1);
        list[fLen] = i;

    }

    public static void main(String[] args) {

        AddItemToArray myArray = new AddItemToArray();
        myArray.push(10);
        myArray.push(20);
        myArray.push(30);
        System.out.println(Arrays.toString(myArray.getList()));

    }
}