简体   繁体   English

使用getter / setter向列表添加元素

[英]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. 每次我调用inserimentoVoto方法在对象Studente中包含的列表中添加元素时,数据就会被覆盖,我知道这很容易,但是我才开始编写代码。

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 您每次都在创建一个新的ArrayList

The above line should be only done once in the Studente class. 上一行仅在Studente类中执行一次。

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. 您根本不需要setListaVoti因为它只完成了一次。

In the inserimentoVoto method, you only need inserimentoVoto方法中,您只需要

s.getListaVoti().add(v);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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