ArrayList Traversal and Summation
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 following getTotal method, which is in a class other than Value, is intended to compute the sum of the num instance variables from all Value objects in valueList.
/** 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, if used to replace /* missing code */, will cause the method to function correctly?
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
II only
B
III only
C
I only
D
I and II
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE