使用getter / setter将元素添加到列表中

时间:2018-03-30 11:45:11

标签: java

每当我调用方法inserimentoVoto来添加对象Studente中包含的列表中的元素时,数据都会被覆盖我知道它很简单,但我刚刚开始编码。< / p>

public class Run {

    public static void main(String[] args) {

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

        g.inserimentoVoto(s);

    }
}

这是方法

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

1 个答案:

答案 0 :(得分:2)

import os

line = "Pacific_Rim;400;126;116;106"
elements_in_line = line.strip(";").split (";")
number_of_columns = len(elements_in_line)

if number_of_columns != 5:
    print ("It's a warning")

您每次都在创建一个新的ArrayList

上述行只能在Studente课程中完成一次。

s.setListaVoti(new ArrayList<Voto>());

您根本不需要public class Studente { private ArrayList<Voto> arr = new ArrayList<Voto>(); ... Other data ... public ArrayList<Voto> getListaVoti() { return arr; } ... Other methods ... } - 因为它只完成了一次。

setListaVoti方法中,您只需要

inserimentoVoto