| preferred AP College board partner for AP classes
AP Computer Science A/Unit 7: ArrayList
Start Practice Test
Share
easy Solved by 4 students
Logical Error in ArrayList Element Swap
< Prev
Next >

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.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Time
Score
#1kaisuki11 0m 00s 100
#2upadhgau00011 0m 00s 100
#3singhris00011 0m 29s 71
APFIVE © 2020.
Email: [email protected]|Privacy Policy