Home > Software design >  Arraylist doesn't add
Arraylist doesn't add

Time:12-29

I've a problem that I don't understand about adding an element into the ArrayList. The result show me that it hasnt added the two computers. Someone can help me ?

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

The result is:

Numero computers: 0

CodePudding user response:

You initialize computers to be an empty list.

List computers = new ArrayList();

Then you add two computers to your list.

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

At this point, your computers list will contain two computers. The size of the list will be two.

Then you assign a new value to the computers list in your second try/catch block. By doing this, you lose the list you had created and populated before. After this, computers will be a completely new list.

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