Comparable Interface

Comparable Interface

In this tutorial, we are going to discuss comparable interface in java. A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances. 

Comparable Interface

This interface is found in java.lang package and contains only one method named compareTo(Object).

public int compareTo(Object obj)

E.g

obj1.compareTo(obj2)

returns

–ve if obj1 has to come before obj2.
+ve if obj1 has to come after obj2.
0 if obj1 and obj2 are equal(Duplicate Objects).
package com.ashok.collections;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyComparable {
   public static void main(String[] args) {
      System.out.println("A".compareTo("Z"));
      System.out.println("Z".compareTo("K"));
      System.out.println("A".compareTo("A"));
   }
}

Output

-25
15
0

Using Comparable interface, we can sort the elements of:

  1. String objects
  2. Wrapper class objects, for example, Integer, Long etc
  3. User-defined custom objects

Note

  • While Inserting the objects into the TreeSet JVM internally uses compareTo() method.
  • Sometimes we have to define our own customized sorting order, then we should go for comparator Interface.
Java Comparable Example

Let’s see the example of the Comparable interface that sorts the list elements based on age.

package com.ashok.collections;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class Student implements Comparable<Student> {
	int rollno;
	String name;
	int age;

	Student(int rollno, String name, int age) {
		this.rollno = rollno;
		this.name = name;
		this.age = age;
	}

	@Override
	public int compareTo(Student st) {
		if (age == st.age)
			return 0;
		else if (age > st.age)
			return 1;
		else
			return -1;
	}
}
package com.ashok.collections;

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

/**
 * 
 * @author ashok.mariyala
 *
 */
public class ComparableTest {
	public static void main(String args[]) {
		List<Student> al = new ArrayList<>();
		al.add(new Student(101, "Vijay", 23));
		al.add(new Student(106, "Ajay", 27));
		al.add(new Student(105, "Jai", 21));

		Collections.sort(al);
		for (Student st : al) {
			System.out.println(st.rollno + " " + st.name + " " + st.age);
		}
	}
}

Output

106 Ajay 18
101 Ashok 22
105 Vinod 24

That’s all about the Comparable Interface in java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

Comparable Interface
Scroll to top