使用CSV文件将对象添加到arrayList,但对象的值返回null

时间:2018-02-17 21:34:00

标签: java csv object arraylist

我尝试使用CSV文件创建员工对象列表,但我目前每个值都为null。值为:username,firstname,lastname,email,gender,race,id和ssn。我可以在CSV文件中读取并解析它,但是当我尝试使用对象填充列表时,它会填充它们,但每个值仍然为空。主要方法:

public static void main(String[] args) {
    String csvFile = "employee_data.csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";
    List<Entry> People = new ArrayList<>();
    try {
        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {
            // use comma as separator
            String[] Labels = line.split(cvsSplitBy);                 
            Entry entry = new Entry(Labels[0], Labels[1], Labels[2], Labels[3], Labels[4], Labels[5], Labels[6], Labels[7]);
            People.add(entry);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.print(People);
}

入门课程:

public class Entry {
    private String Username, Firstname, Lastname, Email, Gender, Race, ID, SSN;
    public Entry(String Username, String Firstname, String Lastname, String Email, String Gender, String Race, String ID, String SSN) {
        this.Username=null;
        this.Firstname=null;
        this.Lastname=null;
        this.Email=null;
        this.Gender=null;
        this.Race=null;
        this.ID=null;
        this.SSN=null;
    }
    @Override
    public String toString() {
        return ("Username:"+this.Username);
    }
}

我不确定为什么Entry对象被正确地添加到List中,但是Labels数组中的值没有被传输,所以username,firstname等都被标记为null而我无法弄清楚为什么

1 个答案:

答案 0 :(得分:0)

我认为Entry类的构造函数需要将参数分配给类中的字段。如下:

public class Entry {

    private String Username, Firstname, Lastname, Email, Gender, Race, ID, SSN;

    public Entry(String Username, String Firstname, String Lastname, String Email, String Gender, String Race, String ID, String SSN) {
        this.Username = Username;
        this.Firstname = Firstname;
        this.Lastname = Lastname;
        this.Email = Email;
        this.Gender = Gender;
        this.Race = Race;
        this.ID = ID;
        this.SSN = SSN;
    }

    @Override
    public String toString() {
        return ("Username:" + this.Username);
    }
}