简体   繁体   中英

Adding elements to list using getter/setter

Every time I call the method inserimentoVoto to add elements in a list contained in the object Studente , the data is overwritten I know it's easy but I just started to code.

public class Run {

    public static void main(String[] args) {

        Gestione g = new Gestione();
        Studente s = new Studente();

        g.inserimentoVoto(s);

    }
}

This is the method

public void inserimentoVoto(Studente s) {

        Voto v = new Voto();
        System.out.println("Insert value");
        v.setVoto(scanner.next());
        System.out.println("Insert name");
        v.setMateria(scanner.next());
        v.setDataVoto(new Date());

        s.setListaVoti(new ArrayList<Voto>());
        s.getListaVoti().add(v);
    }
s.setListaVoti(new ArrayList<Voto>());

You are creating a new ArrayList everytime

The above line should be only done once in the Studente class.

public class Studente 

{

private ArrayList<Voto> arr = new ArrayList<Voto>();

... Other data ...

public ArrayList<Voto> getListaVoti()
{
     return arr;
}

... Other methods ...

}

You do not need a setListaVoti at all - because it's done only once.

In the inserimentoVoto method, you only need

s.getListaVoti().add(v);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM