Limited access

Consider the following method.

// Pre-condition: The ArrayList contains at least one element
public static int sumValues(ArrayList<Integer> list)
{
int sum=0;
for (int i=0; i<list.size(); i++)
{
if(i==0)
sum+=list.get(i);
else
if (i==list.size()-1)
sum+=list.get(i);
else
sum+=0
}
return sum;
}


Which of the following methods would be the BEST alternative to make this method run faster, on average?

The end result needs to be the same in all situations.

A
// Pre-condition: The ArrayList contains at least one element
public static int sumValues(ArrayList<Integer> list)
{
if (list.size()>1)
return list.get(0) + list.get(list.size()-1);
else
return list.get(0);
}

B
// Pre-condition: The ArrayList contains at least one element
public static int sumValues(ArrayList<Integer> list)
{
return list.get(0) + list.get(list.size()-1);
}

C
// Pre-condition: The ArrayList contains at least one element
public static int sumValues(ArrayList<Integer> list)
{
int sum=0;
for (int i=0; i<list.size(); i++)
{
if(i==0)
sum+=list.get(i);
else
if(i==list.size()-1)
sum+=list.get(i);
}
return sum;
}

D
// Pre-condition: The ArrayList contains at least one element
public static int sumValues(ArrayList<Integer> list)
{
int sum=0;
for (int i=0; i<list.size(); i++)
{
if(i==0)
sum+=list.get(i);
else
sum+=list.get(i);
}
return sum;
}

E
// Pre-condition: The ArrayList contains at least one element
public static int sumValues(ArrayList<Integer> list)
{
int x=0;
int sum= list.get(0);
for (int i=0; i<list.size(); i++)
{
x=i;
}
return sum+list.get(x);
}

Select an assignment template