Comparable vs Comparator

   Quality Thought is recognized as the best software testing institute in Hyderabad, offering top-notch training in manual testing, automation testing, and full stack testing tools. With a focus on industry-relevant curriculum and hands-on practice, Quality Thought prepares students for real-world software testing challenges. The institute provides expert-led training on popular tools and frameworks like Selenium, TestNG, Jenkins, Git, Postman, JIRA, Maven, and Cucumber, covering both frontend and backend testing essentials.


Quality Thought’s Full Stack Testing course is specially designed to make students proficient in both manual testing fundamentals and automated testing tools, along with exposure to API testing, performance testing, and DevOps integration. The institute stands out for its experienced trainers, live projects, placement support, and flexible learning options including classroom and online modes.


Whether you are a fresher aiming for a job or a working professional looking to upskill, Quality Thought offers customized learning paths. Its strong industry connections ensure regular placement drives and job interview 

Comparable vs Comparator

In Java, Comparable and Comparator are interfaces used to sort objects, but they serve different purposes and are used in different ways.


Comparable:

It is found in the java.lang package.


A class implements Comparable<T> to define its natural ordering.


It has a single method: int compareTo(T o).


You override this method to compare the current object (this) with another.


Example:


java

Copy

Edit

public class Student implements Comparable<Student> {

    int marks;

    public int compareTo(Student s) {

        return this.marks - s.marks;

    }

}

Sorting is done using Collections.sort(list);


Comparator:

It is in the java.util package.


It is used to define custom ordering of objects, especially when the class doesn’t implement Comparable.


It has a method: int compare(T o1, T o2).


You can create multiple comparators for different sorting logic.


Example:


java

Copy

Edit

Comparator<Student> nameComp = (a, b) -> a.name.compareTo(b.name);

Collections.sort(list, nameComp);

Key Differences:

Comparable affects the original class; Comparator doesn’t.


Comparable has only one sorting logic; Comparator allows multiple.


Use Comparable when default ordering is needed, and Comparator for flexible, custom sorting.


Conclusion:

Use Comparable for natural, default sorting and Comparator for custom sorting logic, especially when sorting the same class by different attributes.

Read More

Iterator and ListIterator

HashMap, TreeMap

HashSet, TreeSet

ArrayList, LinkedList

Visit Quality Thought Institute Hyderabad


Comments

Popular posts from this blog

What is Tosca and what is it used for?

Compute Engine (VMs)

What is Software Testing