Difference between Comparable and Comparator in Java

Often we are in a situation where we need to compare/sort objects of the same type. For example: compare two student objects based on their marks and sort them; compare two string objects. For the very purpose, java provides two interfaces Comparable and Comparator. Both of them are used to compare the objects, but they are used according to system design and usage. For example, if you want to have only one type of ordering you can use Comparable interface while if you want to define the multiple types of ordering you can use Comparator interface and define multiple comparators.

Let us understand Comparable and Comparator interface in detail. Further, we will understand the difference between them and their usage in programming.

Comparable Interface

Comparable interface provides only one method i.e compareTo() method which is required to be implemented by class for which comparison is required. The signature of compareTo method is

public int compareTo(T o);

Let us create a Student class and implement Comparable interface and define ordering based on the id of the student object.

public class Student implements Comparable{
	private Integer id;
	private String name;
	private double marks;
	
	public Student(Integer id, String name, double marks){
		this.id = id;
		this.name =  name;
		this.marks = marks;
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getMarks() {
		return marks;
	}
	public void setMarks(double marks) {
		this.marks = marks;
	}
	@Override
	public int compareTo(Student student1) {
		return this.id - student1.id;
	}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ComparableDemo {
	public static void main(String[] args) {
		List students = new ArrayList();
		students.add(new Student(3,"Amit",77.7));
		students.add(new Student(2,"Ashish",77.73));
		students.add(new Student(1,"Deepak",73.73));
		Collections.sort(students);
		 for (Student student : students) {
	            System.out.println(student.getId() + ", " + student.getName()  + ", " +student.getMarks() );
	        }
	}
}
1, Deepak, 73.73
2, Ashish, 77.73
3, Amit, 77.7

In the above code snippet, Student class has implemented the Comparable interface and its method compareTo(). In this method, the comparison between two student objects is done based on the ids of student object. Now let us run the program and we found the output sorted based on the Ids of student as displayed above.

Now the question arises, what if we want to have multiple ordering i.e based on marks, based on Id, based on percentage. Moreover, we don't have access to source code of student class for modification. The above design can be achieved using Comparator interface in Java. Let us understand Comparator interface in Java.

Comparator Interface

The Comparator interface provides compare() method which should be implemented to create ordering comparators. Using Comparator, we can write different comparators based on different attributes of any class. In the below example, we have created two different comparators, one based on the name of the student and another based on the id of the student. 

public class Student {
	private Integer id;
	private String name;
	private double marks;
	
	public Student(Integer id, String name, double marks){
		this.id = id;
		this.name =  name;
		this.marks = marks;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getMarks() {
		return marks;
	}
	public void setMarks(double marks) {
		this.marks = marks;
	}
	
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparatorDemo {
	public static void main(String[] args) {
		List students = new ArrayList();
		students.add(new Student(3,"Amit",77.7));
		students.add(new Student(2,"Ashish",77.73));
		students.add(new Student(1,"Deepak",73.73));
		System.out.println("***Sorting By Student Id***");
		Collections.sort(students, new Comparator(){
			@Override
			public int compare(Student student1, Student student2) {
				return student1.getId() - student2.getId();
				
			}
		});
		for (Student student : students) {
	            System.out.println(student.getId() + ", " + student.getName()  + ", " +student.getMarks() );
	    }
		System.out.println("***Sorting By Student Name***");
		Collections.sort(students, new Comparator(){
			@Override
			public int compare(Student student1, Student student2) {
				return student1.getName().compareTo(student2.getName());
				
			}
		});
		for (Student student : students) {
	            System.out.println(student.getId() + ", " + student.getName()  + ", " +student.getMarks() );
	    }
	}
}
***Sorting By Student Id***
1, Deepak, 73.73
2, Ashish, 77.73
3, Amit, 77.7
***Sorting By Student Name***
3, Amit, 77.7
2, Ashish, 77.73
1, Deepak, 73.73

The output displays that the first comparator is used to sort list of student objects based on their ids while the another one is used to sort the list of students based on their name. The similar implementation can be done to sort students based on their marks.

Try to create a new Comparator and sort the list of students based on their marks.

Difference between Comparator and Comparable interface

Though both Comparable and Comparator interfaces are used to compare objects based on their attribute values, their implementation varies based on the design approach of program and software. Let us check the difference between Comparator and Comparable interface and their usage while implementation.

  Comparable Comparator
Implementation Comparable interface should be implemented by the class whose objects must be sorted. Hence, it is necessary to have source code of implementing class to use comparable interface. Comparator interface can be implemented by any third class or even we can create anonymous class to sort the object of other classes. For example: In above code snippet, we created anonymous class in ComparatorDemo class and implemented Comparator interface to sort Student class objects.
Number of Comparision Type As Comparable interface provides one method compareTo() and must be implemented by the class required for sorting, we can have only one ordering strategy. For example in Student class we implemented ordering based on the ids. comparator interface can be used to create multiple ordering strategies/approaches based on the attributes of the objects. For example: we created two sorting techniques based on the ids and name.
Package It is available in java.lang package. It is available in java.util package.
Author
Author: Amit Gupta
Published On: 06/09/2015
Last revised On: 13/11/2015
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media