AP Computer Science A · Topic 7.6
Sorting Practice
Part of ArrayList.
Practice questions
33
Sample questions
5 of 33 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
public class Item implements Comparable<Item> { private int v; public Item(int x) { v = x; } public int compareTo(Item o) { if (v < o.v) return -1; if (v > o.v) return 1; return 0; } } // Usage: Item a = new Item(5); Item b = new Item(5); System.out.print(a.compareTo(b));What is printed?
- A
-1
- B
5
- C
1
- Dcheck_circle
0
Why
Equal values lead to compareTo returning 0. This is a valid (and safer) compareTo implementation that avoids overflow.
- A
Sample 2difficulty 2/5
String a = "cat"; String b = "cat"; int r = a.compareTo(b);What is r?
- A
3
- Bcheck_circle
0
- C
1
- D
-1
Why
Equal strings yield 0 from compareTo.
- A
Sample 3difficulty 2/5
String a = "apple"; String b = "banana"; int r = a.compareTo(b);What is true about r?
- A
r is 1 always
- B
r == 0
- C
r > 0
- Dcheck_circle
r < 0
Why
"apple" precedes "banana" lexicographically, so compareTo returns a negative value.
- A
Sample 4difficulty 2/5
int[] a = {7, 3, 9, 1, 5}; java.util.Arrays.sort(a); int median = a[a.length / 2];What is median?
- A
3
- B
9
- Ccheck_circle
5
- D
7
Why
Sorted: {1,3,5,7,9}; index 2 is 5, the median.
- A
Sample 5difficulty 2/5
ArrayList<String> list = new ArrayList<String>(); list.add("banana"); list.add("apple"); list.add("cherry"); // After Collections.sort(list): System.out.print(list.get(0));What is printed?
- A
Compile error: String not Comparable
- B
banana
- C
cherry
- Dcheck_circle
apple
Why
String implements Comparable<String> using lexicographic order. After sorting, "apple" comes first.
- A