Unit 4 Cycle 2 Day 17: ArrayList: compareTo Sorting
Share
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.
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.