Logical Error in ArrayList Element Swap
What logical error prevents swapElements from properly swapping two elements?
import java.util.ArrayList;
public class DebugExample {
public static void main(String[] args){
ArrayList<Integer> nums = new ArrayList<>();
nums.add(1);
nums.add(2);
nums.add(3);
swapElements(nums, 0, 2);
System.out.println(nums);
}
public static void swapElements(ArrayList<Integer> list, int i, int j) {
list.set(i, list.get(j));
list.set(j, list.get(i));
}
}
A
The ArrayList is not properly imported, causing a compilation error.
B
The indices passed to the method are out-of-bounds.
C
The swapElements method should use add() rather than set() to interchange elements.
D
The method fails to use a temporary variable to store one of the elements before overwriting, which results in both indices ending up with the same value.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | kaisuki | 1 | 1 | 0m 00s | 100 |
| #2 | upadhgau000 | 1 | 1 | 0m 00s | 100 |
| #3 | singhris000 | 1 | 1 | 0m 29s | 71 |
APFIVE