Logical Error in ArrayList Element Swap
Consider the following Java code. What is the logical error in the swapElements method that prevents it from correctly 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 indices passed to the method are out-of-bounds.
B
The ArrayList is not properly imported, causing a compilation error.
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 | bommasam000 | 2 | 2 | 1m 31s | 109 |
| #2 | upadhgau000 | 1 | 1 | 0m 00s | 100 |
| #3 | kaisuki | 1 | 1 | 0m 00s | 100 |
| #4 | singhris000 | 1 | 1 | 0m 29s | 71 |
Items per page:
10
1 – 4 of 4
APFIVE