Comparable Implementation in Java: Explanation & Practice

Implement Comparable for sorting

Problem summary

Create a Student class that implements Comparable to sort by grade.

Starter code

import java.util.*;

// Student implements Comparable<Student>
// compareTo() based on grade (higher first)

public class Main {
    public static void main(String[] args) {
        // Create list, sort, print top student
    }
}

Expected output and test cases

  • Highest grade first
    Top student: Alice (95)
  • Different top
    Top student: Bob (88)
  • Perfect score
    Top student: Carol (100)

Hints

  1. compareTo returns negative, zero, or positive
  2. For descending: other.grade - this.grade
  3. Collections.sort() uses compareTo

Related Inheritance exercises

Practice all Inheritance exercises · Run this idea in the Java compiler