Free Data Structures and Algorithms Course

Subscribe below and get all best seller courses for free !!!


Subscribe for all free courses

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)
 { = name; 
  this.percentage = percentage;

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

 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);


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


Output of the program :

© 2021 Learn Java by Examples Template by Hubberspot