当我想从文件创建一个 ArrayList 时,我是否在从文件实例化一个对象? Java

Am I Instantiating an Object from File, when I want to create an ArrayList from File? Java

我们被分配将文本文件转换为几何对象的 ArrayList。问题是我不知道我是把它转换成 ArrayList 还是只是实例化一个对象? Eclipse 声称我没有使用过 ArrayList 库

文本文件看起来像这样:

圆形,红色,false,4.0

圆形,蓝色,真,2.0

圆形,蓝色,真,10.0

矩形,黄色,真,10.0,6.0

矩形,绿色,真,5.0,11.0

矩形,红色,真,20.0,15.0

到目前为止我已经用我的代码完成了这个:

public class Driver {

    public static void main(String[] args) throws FileNotFoundException {

        GeometricObject g = null;
        File diskFile = new File("e:/temp/obj.txt");
        Scanner diskScanner = new Scanner(diskFile);
        while (diskScanner.hasNext()) {
            String list = diskScanner.nextLine();

            g = recreateObject(list);
        }
        diskScanner.close();
    }

    private static GeometricObject recreateObject(String list) {

        String[] data = list.split(",");
        String geoObject = data[0];

        if (geoObject.equals("Circle")) {
            String color = data[1];
            boolean filled = Boolean.valueOf(data[2]);
            double radius = Double.valueOf(data[3]);
            return new Circle(color, filled, radius);
        }

        if (geoObject.equals("Rectangle")) {
            String color = data[1];
            boolean filled = Boolean.valueOf(data[2]);
            double length = Double.valueOf(data[3]);
            double width = Double.valueOf(data[4]);
            return new Rectangle(color, filled, length, width);
        }

        return null;
    }
}

我想将每个 GeometricObject 存储到一个 "ArrayList list = new ArrayList();" [尚未实现] 但我不确定该怎么做。

只需在 while 循环外声明 ArrayList,然后在循环内添加新对象 g...

List<GeometricObject> geoList = new ArrayList<GeometricObject>();
while(diskScanner.hasNext()){
    String list = diskScanner.nextLine();
    g = recreateObject(list);

    geoList.add(g);

}