Malika Gulati’s Post

I am on my journey to master Java’s most confusing interview concepts, and I thought of sharing a few learnings here 🚀 Today, I tackled one of the most commonly asked (and confusing) topics: Comparator vs Comparable 🔹 Comparable An interface that provides the compareTo() method where we define the default sorting logic • Defined inside the class • Supports only ONE sorting logic eg- class Student implements Comparable<Student> { int marks; public int compareTo(Student other) { return Integer·compare(this.marks, other.marks); } } 🔹 Comparator An interface that provides the compare() method for custom sorting • Defined outside the class • Supports MULTIPLE sorting logics eg- list.sort((a, b) -> Integer·compare(a.marks, b.marks)); // sort by marks list.sort((a, b) -> a.name.compareTo(b·name)); // sort by name 🔥 The real takeaway ✔ Comparable → One default behavior ✔ Comparator → Many dynamic behaviors ⚡ Interview trap (important) ❌ Don’t write: return a - b; 👉 Can cause integer overflow ✅ Always prefer: Integer·compare(a, b); 🧠 Mental note Ascending → (a, b) Descending → (b, a) If you're preparing for Java interviews, mastering this concept can save you from a LOT of confusion 🤯 #Java #DSA #InterviewPrep #BackendDevelopment #Programming #SoftwareEngineering

To view or add a comment, sign in

Explore content categories