Unit 3 Cycle 2 Day 20: Polymorphism: Object Array Sorting

Unit 3 Advanced (Cycle 2) Day 20 of 28 Advanced

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.

public class Student { private String name; private double gpa; public Student(String n, double g) { name = n; gpa = g; } public double getGPA() { return gpa; } public String getName() { return name; } } Student[] arr = {new Student("Bo", 3.5), new Student("Al", 3.8), new Student("Jo", 3.2)}; Student best = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i].getGPA() > best.getGPA()) { best = arr[i]; } } System.out.println(best.getName());

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.

Review this topic: Section 3.15 — Creating References • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

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