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
- compareTo returns negative, zero, or positive
- For descending: other.grade - this.grade
- Collections.sort() uses compareTo
Related Inheritance exercises
- Practice Bank Account Types in Java
- Practice Multiple Interfaces in Java
- Practice Template Method Pattern in Java
Practice all Inheritance exercises · Run this idea in the Java compiler