我有一个对象 Activity
初始化时,看起来像 Activity a = new Activity(String activityName, double calories)
。我有另一个对象,ActivityPerformed
初始化时,看起来像 ActivityPerformed ap = new ActivityPerformed(Activity a, double hours
)。我也有两个ArrayLists
( Activity
和 ActivityPerformed
的数组)和 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>
时,所有输入的 Activity 都在那里,但是当我打印 ArrayList<ActivityPerformed>
时它总是打印 double
( calories
和 hours
)为 0.0,而 activityName
为 null 但它打印了正确的项目数。
这是我添加到 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>
获取 Activity 并向其附加一个额外的字段,并使其不打印 null
?
最佳答案
罪魁祸首是 ActivityPerformed 构造函数中的这一行
a = new Activity(name, calories);
它应该将传递的 Activity 分配给 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/