Summing ArrayList Elements
Consider the following Value class definition.
public class Value
{
private int num;
public int getNum()
{
return num;
}
// There may be instance variables, constructors, and methods not shown.
}
The getTotal method, shown below, appears in a class other than Value. It is intended to compute the sum of the num instance variables for all Value objects in its ArrayList parameter.
/** Precondition: valueList is not null */
public static int getTotal(ArrayList<Value> valueList)
{
int total = 0;
/* missing code */
return total;
}
Which of the following code segments, when substituted for /* missing code */, will cause the getTotal method to work as intended?
I.
for (int x = 0; x < valueList.size(); x++)
{
total += valueList.get(x).getNum();
}
II.
for (Value v : valueList)
{
total += v.getNum();
}
III.
for (Value v : valueList)
{
total += getNum(v);
}
A
III only
B
I only
C
II only
D
I and II
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE