Arraylist 不添加

Arraylist doesn't add

我有一个关于向 ArrayList 添加元素的问题,我不明白。 结果告诉我它没有添加两台计算机。 有人可以帮助我吗?

    Computer computer;
    GenerateXML xml;
    Parser dom = new Parser();
    List computers = new ArrayList();
    computer = new Computer("2", "fisso", "Corsair", "Venom 2X", 1029971511, 4.5f, 12, 32, 600, 24.0f, 1900, "Linux", "21-10-2021");
    computers.add(computer);
    computer = new Computer("3", "laptop", "Microsoft", "Surface", 1000091801, 4.5f, 12, 32, 600, 24.0f, 1900, "Linux", "21-10-2021");
    computers.add(computer);

    try {
        xml = new GenerateXML(computers);
        xml.printToFile("computer.xml");
    } catch (ParserConfigurationException | TransformerException exception) {
        System.out.println("Errore generate!");
    }

    try{
        computers = dom.parseDocument("computer.xml");
    } catch (ParserConfigurationException | SAXException | IOException exception){
        System.out.println("Errore parsing!");
    }
    System.out.println("Numero computers: " + computers.size());
    for (int i = 0; i < computers.size(); i++)
        System.out.println(computers.get(i));

结果是:

Numero computers: 0

您将计算机初始化为空列表。

List computers = new ArrayList();

然后您将两台计算机添加到列表中。

computer = new Computer("2", "fisso", "Corsair", "Venom 2X", 1029971511, 4.5f, 12, 32, 600, 24.0f, 1900, "Linux", "21-10-2021");
computers.add(computer);
computer = new Computer("3", "laptop", "Microsoft", "Surface", 1000091801, 4.5f, 12, 32, 600, 24.0f, 1900, "Linux", "21-10-2021");
computers.add(computer);

此时,您的计算机列表将包含两台计算机。列表的大小将是两个。

然后您为第二个 try/catch 块中的计算机列表分配一个新值。通过这样做,您将丢失之前创建和填充的列表。在此之后,计算机将是一个全新的列表。

computers = dom.parseDocument("computer.xml");