How to implement Comparable Interface in Java with an example ?

Program to demonstrate how to implement Comparable Interface in Java with an example.

package com.hubberspot.code;

import java.util.ArrayList;
import java.util.Collections;

public class Student implements Comparable {

 public String name;
 public double percentage;

 Student(String name, double percentage)
 {
  this.name = name; 
  this.percentage = percentage;
 }

 public String toString()
 {
  return "\nName = " + name + "\n"+
    "Percentage = " + percentage+"\n";
 }


 @Override
 public int compareTo(Object o) {
  Student other = (Student) o;

  Double percentage1 = (Double) this.percentage;
  Double percentage2 = (Double) other.percentage;

  return percentage1.compareTo(percentage2);

 }


 public static void main(String[] args) {

  ArrayList list = new ArrayList();

  list.add(new Student("Dinesh",76.2));
  list.add(new Student("Jonty",96.5));
  list.add(new Student("Gunjan",81.7));
  list.add(new Student("Parishrut",62.1));

  System.out.println("Before Sorting : \n" + list);

  Collections.sort(list);

  System.out.println("\nAfter Sorting : \n" + list);

 }
}



Output of the program :