Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear a list after adding its elements to another list

Tags:

java

list

I'm doing a program that gets as parameter more sentences. And I made 2 lists, one called "propozitie", which contains each sentence, and one called "propozitii", which contains all sentences.

The problem is: When I clear the "propozitie" list after it meets a ".", it also clears the "propozitii" list and it's ending up by printing 3 empty lists.

Input data:

Andrei goes there. Andrei plays football. I enjoy staying home.

Can anybody help me ? Thanks in advance.

import java.util.ArrayList;
import java.util.List;

public class Propozitie {

private static List<List<String>> propozitii;
private static List<String> propozitie;

public static void main(String args[]) {

    propozitii = new ArrayList<List<String>>();
    propozitie = new ArrayList<String>();

    for (String arg : args) {
        propozitie.add(arg);

        if (arg.contains(".")) {
            propozitii.add(propozitie);
            propozitie.clear();
        }

    }

    System.out.println(propozitii);

}
}
like image 494
Andrei Olar Avatar asked Oct 27 '25 14:10

Andrei Olar


1 Answers

This is because, the statement

propozitii.add(propozitie);

adds the reference to propozitie to propozitii list. A copy of the object is not added. To do a copy, use this.

propozitii.add(new ArrayList<String>(propozitie));

now you can clear propozitie

like image 200
Deva Avatar answered Oct 29 '25 03:10

Deva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!