Unit 3 Cycle 2 Day 20: Polymorphism: Object Array Sorting
Share
Polymorphism: Object Array Sorting
Section 3.15 — Creating References
Key Concept
Sorting an array of objects using polymorphism relies on the compareTo() method or comparison logic in the sorting algorithm. When objects of different subclass types are in the same array, the comparison method must handle all types correctly. The AP exam may present a sorting algorithm that works on a superclass array, with compareTo() overridden differently in each subclass. The sort's behavior depends on which compareTo() version is invoked for each comparison.
Consider the following code.
What is printed?
Answer: (B) Al
Find max GPA: best=Bo(3.5). i=1: Al(3.8)>3.5, best=Al. i=2: Jo(3.2)>3.8 false. best=Al. Prints "Al".
Why Not the Others?
(A) Bo has 3.5, but Al has 3.8 which is higher.
(C) Jo has the lowest GPA (3.2).
(D) getName() returns the name string, not the GPA value.
Common Mistake
The find-max pattern works with objects by comparing a specific field (GPA). The algorithm is the same as finding max in a number array, but uses accessor methods.
AP Exam Tip
Finding the max/min object in an array by a field value is a common AP exam pattern. Initialize best to arr[0], then compare starting from index 1.