153k views
3 votes
Consider the following method definition. The method isReversed is intended to return true if firstList and secondList contain the same elements but in reverse order, and to return false otherwise.

/** Precondition: firstList.size() == secondList.size() */
public static boolean isReversed(ArrayList firstList,
ArrayList secondList) {
for (int j = 0; j < firstList.size() / 2; j++) {
if (firstList.get(j) != secondList.get(secondList.size() - 1 - j)) {
return false;
}
}
return true;
}

The method does not always work as intended. For which of the following inputs does the method NOT return the correct value?

A. When firstList is {1, 3, 3, 1} and secondList is {1, 3, 3, 1}
B. When firstList is {1, 3, 3, 1} and secondList is {3, 1, 1, 3}
C. When firstList is {1, 3, 5, 7} and secondList is {5, 5, 3, 1}
D. When firstList is {1, 3, 5, 7} and secondList is {7, 5, 3, 1}
E. When firstList is {1, 3, 5, 7} and secondList is {7, 5, 3, 3}

1 Answer

3 votes

C

The problem is the value to which j counts to. In the for loop, it says to count j up to half of the size of array 1, which is 4 elements/2, so j<2. So, j will count from 0 to 1. The issue with this, however, is this will only count through the first 2 elements in array 1 and the last 2 elements of array 2.

The only answer where this is an issue is with answer C, as the first 2 elements of array 1 match the last 2 of array 2, but the last element of array 1 does not match array 2.

This method will return true before it checks the last element, so it will improperly mark C as True.

User Prateek Verma
by
8.5k points