简体   繁体   English

ArrayList作为对象属性不保存值

[英]ArrayList as Object attribute doesn't save values

I have an object, with this attributes: 我有一个具有以下属性的对象:

public class Club {

    private String name;
    private ArrayList<Integer> points;
    private int average;

    Club(String name, ArrayList<Integer> points, int average){
        this.name = name;
        this.points = new ArrayList<>();
        this.average = average;

I try to fill the arraylist with points with data from a txt file: 我尝试用来自txt文件的数据点填充arraylist:

        while((currentLine = br.readLine()) != null){

            String name;
            ArrayList<Integer> points = new ArrayList<>();
            int average;
            String[] clubData = currentLine.split(",");
            name = clubData[0];

            int score2 = Integer.parseInt(clubData[2]);
            int score3 = Integer.parseInt(clubData[3]);
            int score4 = Integer.parseInt(clubData[4]);
            int score5 = Integer.parseInt(clubData[5]);

            points.add(score2);
            points.add(score3);
            points.add(score4);
            points.add(score5);

            average = points.stream().mapToInt(Integer::intValue).sum()/4;
            Club club = new Club(name, points, average);

When I print the objects, I get this: 当我打印对象时,得到以下信息:

Name: Clubname Points: [] Average: 6

So, the values of the file are saved in the list. 因此,文件的值将保存在列表中。 Because the average (6) is calculated, and this is the good value. 因为计算了平均值(6),所以这是一个好值。 But, the list 'points' of the object itself is empty. 但是,对象本身的列表“点”为空。 Can anyone explain me this? 谁能向我解释一下?

Your constructor in the Club class is making a new ArrayList every time. 您在Club类中的构造函数每次都会创建一个新的ArrayList。 Change it to this 改成这个

Club(String name, ArrayList<Integer> points, int average){
    this.name = name;
    this.points = points;
    this.average = average;

Your constructor is ignoring points . 您的构造函数忽略了points

Either copy the list (shallow copy): 复制列表(浅复制):

this.points = new ArrayList<>(points);

or keep the reference to the existing list: 或保留对现有列表的引用:

this.points = points;

Additionally, you currently are using Java's integer division to calculate the average. 此外,您当前正在使用Java的整数除法来计算平均值。 Here it looks like it worked out because you aren't complaining that the average is incorrect, but in general you would want to keep your average as a double and divide by a double literal, 4.0 : 在这里看起来像是已经解决了,因为您没有抱怨平均值不正确,但是通常您希望将average保持为double并除以4.0double常量:

average = points.stream().mapToInt(Integer::intValue).sum()/4.0;

Also, an IntStream provides an average calculation for you. 此外, IntStream以为您提供平均计算。 The average method returns an OptionalDouble : average方法返回OptionalDouble

average = points.stream().mapToInt(Integer::intValue).average().getAsDouble();

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

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