Easy learning with example program codes

Comparable interface in java

Comparable interface:

Comparable interface is defined in java.lang package. It has only one method namedcompareTo(Object o).Itis used to implement natural ordering of collection elements. String and wrapper classes implements Comparable interface.

Note: We can sort the elements based on single property only. Suppose we have Student class elements with name, class and rollNo as properties then by using comparable interface we can sort student objects based on single property only either by name or some other one.

Method of Comparable interface:

 compareTo(Object obj): It is used to compare this object with the specified object. It returns +ve integer if this object is greater than the specified object, 0 if this object is equals to the specified object and –ve integer if this object is less than the specified object.

Syntax: public int compareTo(Object obj).

Sorting example using Comparable interface:

 * This class represents a Student and 
 * implements Comparable.
 * @author codesjava
public class Student implements Comparable{
	//data members
	private String name;
	private String rollNo;
	private int age;
	//no-argument constructor
	public Student(){
	//argument cnstructor
	public Student(String name, String rollNo, int age){ = name;
		this.rollNo = rollNo;
		this.age = age;
	public String getName() {
		return name;
	public void setName(String name) { = name;
	public String getRollNo() {
		return rollNo;
	public void setRollNo(String rollNo) {
		this.rollNo = rollNo;
	public int getAge() {
		return age;
	public void setAge(int age) {
		this.age = age;
	//Method for sorting logic
	public int compareTo(Object obj){  
		Student student=(Student)obj;  
		return (;  

 * This class is used to show the sorting functionality.
 * @author codesjava
public class Test {
	public static void main(String args[]){
		ArrayList studentList = new ArrayList();
		studentList.add(new Student("Sandy", "MCA/07/06", 28));
		studentList.add(new Student("Roxy", "MCA/07/32", 28));
		studentList.add(new Student("Sunil", "MCA/07/15", 27));
		studentList.add(new Student("Munish", "MCA/07/04", 27));
		Iterator iterator=studentList.iterator();  
			Student student=(Student);  
			System.out.println("Name: " + student.getName()+
				  ", " + "RollNo: "+student.getRollNo()+
					", Age: "+student.getAge());  


Name: Munish, RollNo: MCA/07/04, Age: 27
Name: Roxy, RollNo: MCA/07/32, Age: 28
Name: Sandy, RollNo: MCA/07/06, Age: 28
Name: Sunil, RollNo: MCA/07/15, Age: 27

Download this example.
Next Topic: Comparator interface in java with example.
Previous Topic: Sorting in java with example.

Copyright © 2018 CodesJava Protection Status SiteMap