Pages

Sunday, 3 September 2023

Comparable vs Comparator in Java with Code examples

 


Java Interview Questions SET-01

Java Interview Questions Set-02 ARRAY

Java Interview Questions Set-03 MAP

Java Interview Question Set-04

In Java, when working with objects, there often arises a need to compare and sort them based on certain criteria. Java provides two essential interfaces, Comparable and Comparator, to facilitate this process.

  • Comparable Interface:

    • The Comparable interface is designed for classes that wish to establish a default way of comparing their instances. It provides a means for defining a natural ordering for objects of the same class.
    • Classes that implement Comparable must override the compareTo() method, which specifies how two objects of that class should be compared.
    • By implementing Comparable, you enable objects of your class to be sorted in their natural order, such as sorting strings alphabetically or numbers numerically.
  • Comparator Interface:

    • On the other hand, the Comparator interface allows you to define custom comparison logic for objects, especially when there isn't a clear natural order or when you want to sort objects in different ways.
    • With Comparator, you can create multiple comparison strategies without modifying the original class.
    • Classes that implement Comparator must define the compare() method, which specifies how two objects should be compared.

Both Comparable and Comparator play crucial roles in Java's sorting and comparison mechanisms, enabling developers to arrange objects effectively based on different criteria and use cases. Understanding when and how to use these interfaces is fundamental in Java programming.

Comparable in Java:

Think of Comparable as a way to give objects a "default" way of being compared. It's like telling objects how to line up in a row. For instance, let's say you have a bunch of toys, and you want to sort them based on their size. Here's a basic example:


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Toy implements Comparable<Toy> {
private String name;
private int size;

public Toy(String name, int size) {
this.name = name;
this.size = size;
}

@Override
public int compareTo(Toy other) {
return Integer.compare(this.size, other.size);
}

@Override
public String toString() {
return name + " (Size: " + size + ")";
}
}

public class ComparableExample {
public static void main(String[] args) {
List<Toy> toys = new ArrayList<>();
toys.add(new Toy("Teddy Bear", 10));
toys.add(new Toy("Doll", 8));
toys.add(new Toy("Toy Car", 12));

Collections.sort(toys);

for (Toy toy : toys) {
System.out.println(toy);
}
}
}




Comparator in Java:

Now, imagine you want to sort the toys based on their name, but the toys themselves don't know how to compare their names. Here's where Comparator it comes in. It's like giving the toys a specific rule for comparison:


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparatorExample {
    public static void main(String[] args) {
        List<Toy> toys = new ArrayList<>();
        toys.add(new Toy("Teddy Bear", 10));
        toys.add(new Toy("Doll", 8));
        toys.add(new Toy("Toy Car", 12));
        Collections.sort(toys, Comparator.comparing(Toy::getName));
        for (Toy toy : toys) {
            System.out.println(toy);
        }
    }
}

How to use Java Generics in Test Automation ?


Conclusion:

In a nutshell, Comparable it is like giving objects a built-in way to compare themselves, while Comparator is like providing a separate instruction manual for comparison. For beginners, Comparable it is handy when objects have a natural way to line up, and Comparator is useful when you want to sort objects based on different criteria. These concepts help you keep things in order, much like arranging items on a shelf.


How do I loop around Array, List and Map?




How to Sort a Hashmap in Java?


Ans: Refer to the link HERE for answer with code.

I hope this helps you understand how to loop around arrays, lists, and maps in Java!


*******************************************************************
For any doubts or career guidance from me, reach out here: https://topmate.io/sidharth_shukla

********************************************************************

****************************************

 SDET Interview Question and Answers

TestNG Interview questions and answers

Jenkins Interview Questions and Answers

Appium Interview Questions and Answers

Selenium Interview Questions and answers

Java Coding Interview Questions and Answers

GIT Interview Questions and Answers


************************************************

✍️AUTHORLinkedIn Profile

************************************************

Learn (API-Microservice)Testing+ Selenium UI Automation-SDET with Self Paced Videos prepared by FAANG employees and LIVE Doubt Session 

SDET TRANING VIDEOS AVAILABLE with Live Doubt Session Check Training Page for Course Content or reach out @whatsapp +91-9619094122. 
This includes classnotes, 500+ interview questions, 3 projects, and a Java Coding question set for product companies along with career guidance from FAANG employees for Automation and SDET.

For more details whatsapp : https://lnkd.in/dnBWDM33

Course_001API Automation +
UI Automation +
Mobile Testing +
ChatGPT For Test Automation +
Jenkins-GIT-Docker
Course_002API Automation +
UI Automation +
Jenkins-GIT-Docker
Course_003API Automation +
ChatGPT for Test Automation +
Jenkins-GIT
Course_004ChatGPT for Test Automation
Course_005API Automation +
Jenkins-GIT

************************************************

*************************************************




SeleniumWebdriver Automation Testing Interview Questions:

https://automationreinvented.blogspot.com/search/label/SeleniumWebdriver

API Testing Interview Question Set:

https://automationreinvented.blogspot.com/2022/03/top-80-api-testing-interview-questions.html

DevOps Interview Q&A:

https://automationreinvented.blogspot.com/2021/11/top-11-devops-interview-questions-and.html 

Kubernetes Interview Question Set

https://automationreinvented.blogspot.com/search/label/Kubernetes

Docker Interview Question Set

https://automationreinvented.blogspot.com/Docker

Linux Interview question Set

https://automationreinvented.blogspot.com/search/label/Linux

Automation Testing/SDET Framework Design

https://automationreinvented.blogspot.com/search/label/FrameworkDesign

Java Related Interview Question Set

https://automationreinvented.blogspot.com/search/label/Java

GIT Interview Question Set:

https://automationreinvented.blogspot.com/2021/09/top-40-git-interview-questions-and.html

Coding Interview Question Set:

https://automationreinvented.blogspot.com/search/label/Coding%20Questions

Mobile Testing Interview Question Set:

https://automationreinvented.blogspot.com/search/label/Mobile%20Testing

Python Interview Question Set for QAE - SDET - SDE:

https://automationreinvented.blogspot.com/search/label/Python

No comments:

Post a Comment