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

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.

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

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Time
Score
#1bommasam00022 1m 31s 109
#2upadhgau00011 0m 00s 100
#3kaisuki11 0m 00s 100
#4singhris00011 0m 29s 71
Items per page:
10
1 – 4 of 4
No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy