Difference between Comparable and Comparator in Java - Testbook.com

Last Updated on Jul 31, 2023
Download As PDF
IMPORTANT LINKS

Comparable and Comparator, both being interfaces, play a crucial role in sorting elements. This article will delve into the key differences between Comparable and Comparator in Java.

Understanding Comparable in Java

In Java, Comparable refers to an object that can be compared with other objects. Numerous built-in classes in Java implement the Comparable interface.

Get 12 Months SuperCoaching @ just

₹3748 ₹1349

Your Total Savings ₹2399
Purchase Now

Defining Comparator in Java

The Comparator interface in Java is used for ordering the objects of user-defined classes. It has the ability to compare two objects of the same class.

Comparing Comparable and Comparator in Java

S.No. Comparable Comparator
1. It allows sorting based on a single attribute. We can sort the collection based on a single element. It allows sorting based on multiple attributes. In this case, we can sort the collection based on multiple elements.
2. It uses the compareTo() method to sort elements. It uses the compare() method to sort elements.
3. It doesn't modify the original class. It also doesn't modify the original class.
4. It is part of the java.lang package. It is part of the java.util package.

Stay updated with the latest information on GATE Exam , including GATE Eligibility Criteria , GATE 2023 , GATE Admit Card , GATE Application Form , GATE Syllabus , GATE Cut off , GATE Previous Year Question Paper , and more.

Also Explore,

More Articles for Key Differences

Frequently Asked Questions

Comparable in Java means an object that can be compared to other objects. There are multiple built-in classes that enforce the Java comparable interface.

A comparator interface is used to collect the objects of user-defined classes. It is also competent in comparing two objects of an identical class.

The main difference is that Comparable supports single-sorting sequences and has compareTo() technique while Comparator supports multiple sorting sequences and uses compare() technique.

Test Series
406.5k Students
SBI PO Mock Test Series 2025 (Pre + Mains)
367 TOTAL TESTS | 13 Free Tests
  • 13 Full Test (Mains)
  • 70 GA/CA Pack
  • 12 Sectional Test (Mains)
  • 89 Chapter Test
  • 2 2025 Trend Based FTs
  • 28 Full Test (Prelims)
  • 45 Most Saved Qs
  • 15 Sectional Test (Prelims)
  • 24 Memory Based Paper
  • 46 Memory Based Sectional Test
  • 23 IBPS Recent Exam MBTs

Get Started
Report An Error