Unit 4 Cycle 2 Day 17: ArrayList: compareTo Sorting

Unit 4 Advanced (Cycle 2) Day 17 of 28 Advanced

ArrayList: compareTo Sorting

Section 4.5 — ArrayList Algorithms

Key Concept

Using compareTo() for sorting ArrayList elements enables custom ordering. For String objects, compareTo() returns negative (first comes before), zero (equal), or positive (first comes after). A sorting algorithm uses these return values to determine swap decisions. The AP exam may present a sorting algorithm with compareTo() calls and ask you to trace the sort, or ask which final order results from a specific comparison method. Understanding compareTo() semantics is essential for object sorting.

Consider the following code segment.

ArrayList list = new ArrayList(); list.add("banana"); list.add("apple"); list.add("cherry"); for (int i = 0; i < list.size() - 1; i++) { if (list.get(i).compareTo(list.get(i + 1)) > 0) { String temp = list.get(i); list.set(i, list.get(i + 1)); list.set(i + 1, temp); } } System.out.println(list);

What is printed?

Answer: (A) [apple, banana, cherry]

One bubble sort pass: i=0: "banana">"apple", swap: [apple, banana, cherry]. i=1: "banana"<"cherry", no swap. Result: [apple, banana, cherry].

Why Not the Others?

(B) The swap at i=0 reorders banana and apple.

(C) cherry stays at the end.

(D) This would be reverse sorted.

Common Mistake

compareTo() > 0 means first string comes after second alphabetically. This performs one pass of bubble sort on Strings.

AP Exam Tip

compareTo returns: negative (before), zero (equal), positive (after) in alphabetical order. Know this for the AP exam.

Review this topic: Section 4.5 — ArrayList Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.