Comparable vs Comparator in Java — Java Technical Interview Questions & Answers
Comparable vs Comparator in Java
Comparable vs Comparator in Java
- Comparable lives inside the class: implement compareTo. That is the natural order — Integer and String already do this. Comparator is a separate class or lambda: compare(a, b). Extra orders without changing the class.
- One compareTo per class. Many Comparators possible: by name, by marks, by date. Collections.sort(list) uses Comparable. Collections.sort(list, cmp) uses Comparator.
- Don’t change Student just to sort by marks another way — write a Comparator.
- Let's take this on the board with one tiny Main class — no extra files. Comparable vs Comparator in Java — sort uses String's natural compare (case-insensitive here). Start from main, go line by line, and stop at each print. That output is the proof for Comparable vs Comparator.
Technical Interview Tip: Comparable = natural compareTo. Comparator = extra order without changing the class.
Code Examples for Comparable vs Comparator in Java
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ravi", "Asha", "Neha");
names = new ArrayList<>(names);
names.sort(String::compareToIgnoreCase);
System.out.println(names);
}
}Comparable vs Comparator in Java — sort uses String's natural compare (case-insensitive here).
How to Explain Comparable vs Comparator in Java to an Interviewer
Where is compareTo?
Inside the class Comparable
When Comparator?
Extra order Without changing the class