我有一个对象Activity,初始化时,它看起来像Activity a = new Activity(String activityName, double calories)。我有另一个对象,ActivityPerformed,初始化后看起来像ActivityPerformed ap = new ActivityPerformed(Activity a, double hours)。我还有两个ArrayLists(由ActivityActivityPerformed组成的数组),并且ArrayList<ActivityPerformed>依赖于Activity中的信息,这就是为什么它必须首先通过该信息的原因。

因此,基本上,信息流将使其等效于此:

Activity a = new Activity(String activityName, double calories);
ActivityPerformed ap = new Activity(String activityName, double calories,
                                 double hours);


因为添加到ArrayList<ActivityPerformed>要求使用其信息的Activity(这就是ActivityPerformed使用Activity a而不是String activityName, double calories的原因)。

如何使信息正确传递?当我打印ArrayList<Activity>时,所有输入的活动都在那里,但是当我打印ArrayList<ActivityPerformed>时,它总是将doublecalorieshours都)打印为0.0,而activityName为空但打印正确的项目数。

这是我添加到ArrayList<ActivityPerformed>的代码

/**
 * Searches for the Activity record associated with the given name
 *
 * @param name the name of the Activity record to look for
 * @return     the Activity record, or null if it does not exist
 */
public Activity getActivity(String name)
{
    for(Activity a : activityBase) {
        if(a.getName().equals(name))
            return a;
    }
    return null;
}
/**
 * Track that a given kind of activity has been performed for a given number
 * of hours. If the given name does not exist in this ActivityBase, or a
 * negative number of hours is given, an error message will appear.
 *
 * @param name  the name of the activity performed
 * @param hours the number of hours that the activity has been performed
 */
public void trackActivity(String name, double hours)
{
    Activity a = getActivity(name);
    activityPerformed.add(new ActivityPerformed(a, hours));
}


这是用于打印ArrayList的代码(这适用于ArrayList,但可能缺少我忽略的内容)

public String getActivityPerformed() {
    String done = "";
    for(ActivityPerformed a : activityPerformed) {
        done += a.getHours();
        done += " hours of ";
        done += a.getName();
        done += ", ";
        done += a.getTotalCalories();
        done += " calories.\n";
    }
    return done;
}


在ActivityPerformed.class下:

public ActivityPerformed(Activity a, double hours){
    a = new Activity(name, calories);
    this.hours = hours;
    this.name = name;
    this.calories = calories;
}
public String getName(){
    return this.name;
}

public double getTotalCalories(){
    return this.calories;
}

public double getTotalCalories(){
    return this.calories;
}


那么,如何使ArrayList<ActivityPerformed>ArrayList<Activity>获取活动并向其附加一个附加字段,并使其不打印null

最佳答案

罪魁祸首是ActivityPerformed构造函数中的这一行

 a = new Activity(name, calories);


它应该将传递的活动分配给var a

this.a = a;
this.name = a.getName();  // you do not need this as Activity has this information
this.calories = a.getCalories();   // you do not need this as Activity has this information
this.hours = hours;


希望这可以帮助;

关于java - ArrayList内容在访问后变为“null”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22123987/

10-10 03:25