COMPARATOR vs COMPARABLE - A Java Surprise You did in School!
Tags: java, sorting, beginners, programming
Published: 2024-03-16 17:19:38

Ever felt like `Comparable` and `Comparator` were taunting you in Java? You're not wrong! These two interfaces can be a bit mysterious at first, even after conquering mountains of tutorials. (Don't worry, I wrestled with them too!) After enough head-scratching and questionable Google searches (Documentation is great, but sometimes you just need a friendly explanation to break things down, FWIW), I finally cracked the code on these confusing critters.

So forget complex explanations and cryptic code! In this blog, we'll break down `Comparable` and `Comparator` with a **down-to-earth analogy** that'll surely seep into your logical minds. Trust Me!

Plus, we'll walk you through a **simple 3-step process** for implementing each one!

So Let's Begin!

## Let's head back to Schooling Days

Ever wonder why students seem to magically line up by **HEIGHT** during school assemblies? It's like they have a built-in sorting algorithm! I am sure you must've also done this!


![Height](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yitokscu3jo2d7qv5o0i.jpeg)

Well, that's kind of what `Comparable` does in Java. It lets objects define their own natural ordering, just like those height-conscious students. No external instructions needed - they just know their place!

Sound's as simple as that… But let's take a closer look at this to understand better!

---

## Comparable: A Natural Order of Students

Comparable is like a default instruction given to the students on how to line up naturally without any additional directions.

So Let's take a Student class just like a real time student in a school.


```
class Student {
    String name;
    int height;
    int weight;

    public Student(String name, int height, int weight) {
        this.name = name;
        this.height = height;
        this.weight = weight;
    }
}
```


> Just like how a student knows naturally to compare as per height with his companions, the same capability can be given to our Student Class in java using the Comparable interface.


![Height Check](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z8tgj5ta325ycd297ozi.jpeg)

So let's implement the Comparable interface and let's make it happen in just 3 steps as below.

## Implementation of Comparable Interface in 3 Steps:

### 1. Implement the Comparable Interface:
To make a class sortable using the natural order, you implement the `Comparable` interface directly in the class.

> "Keep in mind! Comparable interface grants the class the natural ability to compare itself whenever necessary."

```
public class Student implements Comparable<Student> {
 ....
}
```

### 2. Override the compareTo() Method:
Just override the `compareTo()` method inside your class. This method compares the current object (`this`) with another object of the same type (`other`).

> Think of it as the class's superpower, allowing it to compare naturally whenever the need arises.

```
public class Student implements Comparable<Student> {
    String name;
    int height;
    int weight;

    public Student(String name, int height, int weight) {
        this.name = name;
        this.height = height;
        this.weight = weight;
    }

    @Override
    public int compareTo(Student other) {
        // Compare students based on their height
        return this.height - other.height;
    }
}
```

- If the current **object should come before the other object, return a negative integer**.
- If they are **equal, return 0**.
- If the current **object should come after the other object, return a positive integer**.

### 3. Using Comparable:
Once Comparable is implemented, Java's built-in sorting methods will use the natural order defined by the `compareTo()` method.

> Yipee! The magic now happens naturally. The objects get sorted naturally now!

```
Arrays.sort(students);
```

---

## Now let's see a twist in our example..

Imagine if the students were suddenly tasked with lining up by their **WEIGHT** instead of their height! This is something not natural to the students and is a custom defined instruction given to them. 

Just like the teacher guiding the students to line up by weight, the `Comparator` interface in java too provides an external logic to sort objects based on specific criteria.


![WEIGHT CHECK](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uu7csps89u6gh0g3jcuf.jpeg)

So let's implement the `Comparator` interface and let's make it happen in just 3 steps again.

## Implementation of Comparator Interface in 3 Steps:

### 1. Create a Comparator Class:
To implement a `Comparator`, you need to create a separate class that implements the Comparator interface. This interface requires you to define the `compare()` method.

> Keep in mind simple that - Comparator is just a external Instructor! As simple as a teacher at school in our case!

```
import java.util.Comparator;

public class WeightComparator implements Comparator<Student> {
    ....
}
```

### 2. Override the compare() Method: 
Inside the `Comparator` class, you override the `compare()` method. This method takes two objects of the type you're comparing (in this case, Student objects) and returns an integer value based on their comparison.

> Just as a teacher compares one student's weight after another to sort, think of this method as the Java equivalent. It's like having your own personal sorting instructor built right into your code!

```
import java.util.Comparator;

public class WeightComparator implements Comparator<Student> {
    @Override
    public int compare(Student s1, Student s2) {
        // Compare students based on their weight
        return s1.weight - s2.weight;
    }
}
```

- If the current object should come before the other object, return a negative integer.
- If they are equal, return 0.
- If the current object should come after the other object, return a positive integer.

### 3. Use the Comparator:
Once your `Comparator` is defined, you can use it to sort objects in various ways. For example, you can use it with the `Arrays.sort()` method or with collections like `ArrayList`.

> Now, you're putting the teacher to work in your Java program by calling the sort method along with the comparator.

```
Arrays.sort(students, new WeightComparator());
```

---

_Get your coding hands on your keyboards and give this a try! I'm confident it will streamline your programming experience. Remember, don't hesitate to reach out for additional help and suggestions._

## Closing Thoughts:
Thank you for reading our blog. We appreciate your time and interest in our content. If you have any questions, feedback, or topics you'd like us to break open and cook it simpler in our future articles, please feel free to leave a comment below. Your input is valuable, and it helps us create content that matters to you.

Stay connected with us for more insightful articles on various topics related to technology, programming, and much more.

Happy coding!