Pin It

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 :

Please Give Us Your 1 Minute In Sharing This Post!
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
© 2012 Learn Java by Examples Template by Hubber Spot