Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

I need to sort on a list of objects so, I wrote a new class that implements Comparator and it works. Then something popped into my head and I started to wonder if I had used Comparable instead of creating the new class to implement a Comparator. 

Can anyone give me a clear idea on when to use comparable and comparator?

1 Answer

0 votes
by (13.1k points)

A Comparable is used when you are comparing the instances of the same class and a comparator is used when you are comparing instances of different classes.

In case, if you need a different sorting order, then, implement a comparator and define a way of comparing the instances.

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 4, 2021 in Java by RohitSingh (2.6k points)
0 votes
1 answer

Browse Categories

...