Demo of Comparable Interface

 

// Define a class representing a Student class Student implements Comparable<Student> { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } // Implement the compareTo method for natural ordering @Override public int compareTo(Student other) { // Compare students based on their ages return Integer.compare(this.age, other.age); } @Override public String toString() { return "Student{" + "name='" + name + '\\'' + ", age=" + age + '}'; } }

 

import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ComparableDemo { public static void main(String[] args) { List<Student> students = new ArrayList<>(); students.add(new Student("Kevin", 20)); students.add(new Student("Scott", 18)); students.add(new Student("Everett", 22)); System.out.println("Before sorting:"); for (Student student : students) { System.out.println(student); } // Sort students based on natural ordering (age) Collections.sort(students); System.out.println("\\nAfter sorting:"); for (Student student : students) { System.out.println(student); } } }

 

COSC-1437 / ITSE-2457 Computer Science Dept. - Author: Dr. Kevin Roark