The Wayback Machine - https://web.archive.org/web/20240930185458/https://www.geeksforgeeks.org/why-to-use-comparator-interface-rather-than-comparable-interface-in-java/
Open In App

Why to Use Comparator Interface Rather than Comparable Interface in Java?

Last Updated : 22 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java, the Comparable and Comparator interfaces are used to sort collections of objects based on certain criteria. The Comparable interface is used to define the natural ordering of an object, whereas the Comparator interface is used to define custom ordering criteria for an object.

Here are some reasons why you might want to use the Comparator interface over the Comparable interface in Java:

  1. Sorting based on different criteria: When using the Comparable interface, the natural ordering of an object is defined in the class itself. This means that you can only sort objects based on a single criterion. On the other hand, when using the Comparator interface, you can define multiple sorting criteria by creating different instances of the comparator interface. This provides more flexibility when sorting objects.
  2. Sorting objects that do not implement the Comparable interface: If you need to sort objects that do not implement the Comparable interface, you cannot use the Collections.sort() method, which requires objects to implement the Comparable interface. In this case, you can use the Collections.sort() method that takes a Comparator object as a parameter to sort the objects.
  3. Modifying sorting criteria at runtime: When using the Comparator interface, you can modify the sorting criteria at runtime by creating a new instance of the Comparator interface with different sorting logic. This provides more dynamic sorting behavior.
  4. Sorting objects in a different order: When using the Comparable interface, the objects are sorted in natural order, which is not always the desired behavior. When using the Comparator interface, you can define custom sorting criteria to sort objects in a different order.
  5. Separation of concerns: The Comparable interface defines the natural ordering of an object, which may not always be the desired behavior when sorting. When using the Comparator interface, the sorting behavior is separated from the object itself, which provides better encapsulation and separation of concerns.

In summary, the Comparator interface is more flexible and provides more control over the sorting behavior of objects. If you need to sort objects based on different criteria or if the objects do not implement the Comparable interface, you should use the Comparator interface. On the other hand, if you want to define the natural ordering of an object, you should use the Comparable interface.

Prerequisite: Comparable vs Comparator in Java

Throughout the entire lifecycle of the project, we will be creating multiple classes in Java according to our requirements, and sorting is much required in many situations, especially during the report generation, we need to display the data according to the sorted order either in ascending/descending order. Even report generation requires not only single-field sorted order but also multiple fields and also multi-variant sort mechanism is also needed. In that case, we need to depend on Java Comparator Interface which is available in java.util package. Let us take a sample maven java project containing JUnit dependency to look at this feature and justify whether the sorting happens according to our needs or not by using JUnit.

Example Maven Project

Project Structure:

Project Structure

 

This is the maven project containing JUNIT dependencies in

pom.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.gfg.ComparatorServicesInJava</groupId>
    <artifactId>ComparatorServicesInJava</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>5.3.1</junit.version>
        <pitest.version>1.4.3</pitest.version>
    </properties>
 
    <dependencies>
 
        <!-- junit 5, unit test -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
 
    </dependencies>
    <build>
        <finalName>maven-mutation-testing</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M1</version>
            </plugin>
 
            <plugin>
                <groupId>org.pitest</groupId>
                <artifactId>pitest-maven</artifactId>
                <version>${pitest.version}</version>
 
                <executions>
                    <execution>
                        <id>pit-report</id>
                        <phase>test</phase>
                        <goals>
                            <goal>mutationCoverage</goal>
                        </goals>
                    </execution>
                </executions>
 
                <!-- https://github.com/hcoles/pitest/issues/284 -->
                <!-- Need this to support JUnit 5 -->
                <dependencies>
                    <dependency>
                        <groupId>org.pitest</groupId>
                        <artifactId>pitest-junit5-plugin</artifactId>
                        <version>0.8</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <targetClasses>
                        <param>com.gfg.ComparatorServicesInJava.*ComparatorServicesInJava*</param>
                    </targetClasses>
                    <targetTests>
                        <param>com.gfg.ComparatorServicesInJava.*</param>
                    </targetTests>
                </configuration>
            </plugin>
 
        </plugins>
    </build>
 
</project>


Let’s start with the bean class that contains comparisons i.e. sort by  in separate  classes and each class implements a comparator as well specific to

  • Companyname
  • Salary
  • Designation
  • Designation and Salary

Recruitment.java

Java




import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
 
public class Recruitment {
    public Recruitment(String companyName, String employeeName, String designation, double salary,boolean status) {
        super();
        this.companyName = companyName;
        this.employeeName = employeeName;
        this.designation = designation;
        this.salary = salary;
        this.status = status;
    }
 
    public Recruitment() {
        // via setter methods, rest fields are done
    }
 
    String companyName;
    String designation;
    String employeeName;
    double salary;
    boolean status;   
 
    public String getCompanyName() {
        return companyName;
    }
 
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
 
    public String getDesignation() {
        return designation;
    }
 
    public void setDesignation(String designation) {
        this.designation = designation;
    }
 
    public String getEmployeeName() {
        return employeeName;
    }
 
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
 
    public double getSalary() {
        return salary;
    }
 
    public void setSalary(double salary) {
        this.salary = salary;
    }
 
    public boolean isStatus() {
        return status;
    }
 
    public void setStatus(boolean status) {
        this.status = status;
    }
 
    // Method of Recruitment class
    // To print Recruitment details in main()
    public String toString()
    {
  
        // Returning attributes of Recruitment
        return this.companyName + " " + this.employeeName + " "
            + this.designation + " " + this.salary + " " + this.status;
    }
     
    public static void main(String args[]) {
        // Creating an empty ArrayList of Student type
        ArrayList<Recruitment> list = new ArrayList<Recruitment>();
  
        // Adding entries in above List
        // using add() method
        list.add(new Recruitment("abc consultants","Rachel","Analyst",100000.0,true));
        list.add(new Recruitment("nyc consultants","Monica","DBA",90000.0,true));
        list.add(new Recruitment("abc consultants","Phoebe","Programmer",70000.0,true));
        list.add(new Recruitment("nj consultants","Jane","Programmer",80000.0,false));
         
        list.add(new Recruitment("xyz consultants","Ross","ProgramManager",200000.0,true));
        list.add(new Recruitment("chennai consultants","Chandler","ProjectManager",150000.0,true));
        list.add(new Recruitment("xyz consultants","Joe","Programmer",80000.0,true));
        list.add(new Recruitment("mumbai consultants","Any","Programmer",85000.0,false));       
  
        // Display message on console for better readability
        System.out.println("Unsorted order of the details");
  
        // Iterating over entries to print them
        for (int i = 0; i < list.size(); i++)
            System.out.println(list.get(i));
  
        // Sorting the entries by company name
        Collections.sort(list, new GetDataByCompanyName());
         
        System.out.println("\nSorted by CompanyName");
  
        // We will get the sorted order now by company name
        for (int i = 0; i < list.size(); i++)
            System.out.println(list.get(i));
  
        // Sorting the  entries by salary
        Collections.sort(list, new GetDataBySalary());
 
        System.out.println("\nSorted by salary");
  
        // We will get the sorted order now by salary
        for (int i = 0; i < list.size(); i++)
            System.out.println(list.get(i));
         
         // Sorting the  entries by designation
        Collections.sort(list, new GetDataByDesignation());
 
        System.out.println("\nSorted by designation");
  
        // We will get the sorted order now by designation
        for (int i = 0; i < list.size(); i++)
            System.out.println(list.get(i));
         
        // Sorting the  entries by designation and salary
        Collections.sort(list, new GetDataByDesignationAndSalary());
  
        System.out.println("\nSorted by designation and salary");
  
        // We will get the sorted order now by salary
        for (int i = 0; i < list.size(); i++)
            System.out.println(list.get(i));
     
    }
 
}
class GetDataByCompanyName implements Comparator<Recruitment>{
 
    @Override
    public int compare(Recruitment recruitment1, Recruitment recruitment2) {
        return recruitment1.companyName.compareTo(recruitment2.companyName);
    }
 
}
class GetDataBySalary implements Comparator<Recruitment> {
    @Override
    public int compare(Recruitment recruitment1, Recruitment recruitment2) {
        return (int) (recruitment1.salary - recruitment2.salary);
    }
 
}
class GetDataByDesignation implements Comparator<Recruitment> {
    @Override
    public int compare(Recruitment recruitment1, Recruitment recruitment2) {
        return recruitment1.designation.compareTo(recruitment2.designation);
    }
 
}
 
// Using 2 fields to compare
class GetDataByDesignationAndSalary implements Comparator<Recruitment> {
 
    @Override
    public int compare(Recruitment recruitment1, Recruitment recruitment2) {
        int designationComparision = recruitment1.designation.compareTo(recruitment2.designation);
        int salaryComparision = (int) (recruitment1.salary - recruitment2.salary);
        return (salaryComparision == 0) ? designationComparision
                : salaryComparision;
    }
     
}


As we are implementing java.util.comparator, not only the natural order of sorting, based on our requirements, we can sort based on different fields. Hence 4 different classes are introduced to produce the result. Not only on a single field but on more than 1 field also sorting is possible. These are the advantages of using a comparator. If needed, we can put some test data and check for the same in the console

 

Now let us see the testcases to justify the same.

TestComparatorServicesJava.java

Java




import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
 
import java.util.ArrayList;
import java.util.Collections;
 
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
 
public class TestComparatorServicesJava {
    private void addListElements(ArrayList<Recruitment> list) {
        // Adding entries in above List
        // using add() method
        list.add(new Recruitment("abc consultants","Rachel","Analyst",100000.0,true));
        list.add(new Recruitment("nyc consultants","Monica","DBA",90000.0,true));
        list.add(new Recruitment("abc consultants","Phoebe","Programmer",70000.0,true));
        list.add(new Recruitment("nj consultants","Jane","Programmer",80000.0,false));
         
        list.add(new Recruitment("xyz consultants","Ross","ProgramManager",200000.0,true));
        list.add(new Recruitment("chennai consultants","Chandler","ProjectManager",150000.0,true));
        list.add(new Recruitment("xyz consultants","Joe","Programmer",80000.0,true));
        list.add(new Recruitment("mumbai consultants","Any","Programmer",85000.0,false));
    }
   
    @DisplayName("Test check whether sorting done by company name ")
    @Test
    public void testSortByCompanyName() {
        // Creating an empty ArrayList of Recruitment type
        ArrayList<Recruitment> list = new ArrayList<Recruitment>();
  
        addListElements(list);
         
        // Sorting the entries by company name
        Collections.sort(list, new GetDataByCompanyName());
           
        // Assert the data for sorting by company name
        assertEquals(true, list.get(0).getCompanyName().equalsIgnoreCase("abc consultants"));
        assertEquals(true, list.get(1).getEmployeeName().equalsIgnoreCase("Phoebe"));
        assertEquals(true, list.get(2).getDesignation().equalsIgnoreCase("ProjectManager"));
         
        assertTrue(list.get(0).getEmployeeName().equalsIgnoreCase("Rachel"));
        assertTrue(list.get(list.size()-1).getCompanyName().equalsIgnoreCase("xyz consultants"));
        assertTrue(list.get(list.size()-1).getDesignation().equalsIgnoreCase("Programmer"));
                 
    }
   
    @DisplayName("Test check whether sorting done by salary ")
    @Test
    public void testSortBySalary() {
        // Creating an empty ArrayList of Recruitment type
        ArrayList<Recruitment> list = new ArrayList<Recruitment>();
  
        addListElements(list);
         
        // Sorting the entries by company name
        Collections.sort(list, new GetDataBySalary());
           
        // Assert the data for sorting by company name
        assertEquals(true, list.get(0).getCompanyName().equalsIgnoreCase("abc consultants"));
        assertEquals(true, list.get(1).getCompanyName().equalsIgnoreCase("nj consultants"));
        assertEquals(true, list.get(2).getSalary() == 80000.0);
         
        assertTrue(list.get(0).getEmployeeName().equalsIgnoreCase("Phoebe"));
        assertTrue(list.get(list.size()-1).getCompanyName().equalsIgnoreCase("xyz consultants"));
        assertTrue(list.get(list.size()-1).getDesignation().equalsIgnoreCase("ProgramManager"));
        assertTrue(list.get(0).getSalary() == 70000.0);
        assertTrue(list.get(list.size()-1).getSalary() == 200000.0);
                 
    }
   
    @DisplayName("Test check whether sorting done by designation ")
    @Test
    public void testSortByDesignation() {
        // Creating an empty ArrayList of Recruitment type
        ArrayList<Recruitment> list = new ArrayList<Recruitment>();
  
        addListElements(list);
         
        // Sorting the entries by Designation
        Collections.sort(list, new GetDataByDesignation());
           
        // Assert the data for sorting by company name
        assertEquals(true, list.get(0).getCompanyName().equalsIgnoreCase("abc consultants"));
        assertEquals(true, list.get(1).getCompanyName().equalsIgnoreCase("nyc consultants"));
        assertEquals(true, list.get(2).getSalary() == 200000.0);
         
        assertTrue(list.get(0).getEmployeeName().equalsIgnoreCase("Rachel"));
        assertTrue(list.get(list.size()-1).getCompanyName().equalsIgnoreCase("chennai consultants"));
        assertTrue(list.get(list.size()-1).getDesignation().equalsIgnoreCase("ProjectManager"));
        assertTrue(list.get(0).getSalary() == 100000.0);
        assertTrue(list.get(list.size()-1).getSalary() == 150000.0);
                 
    }
     
    @DisplayName("Test check whether sorting done both designation and salary ")
    @Test
    public void testSortByBothDesignationAndSalary() {
        // Creating an empty ArrayList of Recruitment type
        ArrayList<Recruitment> list = new ArrayList<Recruitment>();
  
        addListElements(list);
         
        // Sorting the entries by designation and salary
        Collections.sort(list, new GetDataByDesignationAndSalary());
           
        // Assert the data for sorting by designation and salary
        assertEquals(true, list.get(0).getCompanyName().equalsIgnoreCase("abc consultants"));
        assertEquals(true, list.get(1).getCompanyName().equalsIgnoreCase("nj consultants"));
        assertEquals(true, list.get(2).getSalary() == 80000.0);
         
        assertTrue(list.get(0).getEmployeeName().equalsIgnoreCase("Phoebe"));
        assertTrue(list.get(list.size()-2).getCompanyName().equalsIgnoreCase("chennai consultants"));
        assertTrue(list.get(list.size()-2).getDesignation().equalsIgnoreCase("ProjectManager"));
        assertTrue(list.get(3).getSalary() == 85000.0);
        assertTrue(list.get(list.size()-1).getSalary() == 200000.0);
        assertTrue(list.get(list.size()-1).getDesignation().equalsIgnoreCase("ProgramManager"));
    }
}


Let us see the output and from here we can understand that comparisons can be done on any field and even on more than one field.

 



Previous Article
Next Article

Similar Reads

Comparable vs Comparator in Java
Java provides two interfaces to sort objects using data members of the class: ComparableComparatorUsing Comparable Interface A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances. Consider a Movie class that has members like, rating, name,
6 min read
Stream sorted (Comparator comparator) method in Java
Stream sorted(Comparator comparator) returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when p
3 min read
Java | Collectors maxBy(Comparator comparator) with Examples
Collectors maxBy(Comparator<? super T> comparator) is used to find an element according to the comparator passed as the parameter. It returns a Collector that produces the maximal element according to a given Comparator, described as an Optional<T>. Syntax: public static <T> Collector<T, ?, Optional<T>> maxBy(Comparato
3 min read
Java | Collectors minBy(Comparator comparator) with Examples
Collectors minBy(Comparator<? super T> comparator) is used to find an element according to the comparator passed as the parameter. It returns a Collector that produces the minimal element according to a given Comparator, described as an Optional<T>. Syntax: public static <T> Collector<T, ?, Optional<T>> minBy(Comparato
4 min read
Comparable Interface in Java with Examples
The Comparable interface is used to compare an object of the same class with an instance of that class, it provides ordering of data for objects of the user-defined class. The class has to implement the java.lang.Comparable interface to compare its instance, it provides the compareTo method that takes a parameter of the object of that class. In thi
4 min read
Comparator Interface in Java with Examples
A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Following function compare obj1 with obj2. Syntax: public int compare(Object obj1, Object obj2):Suppose we have an Array/ArrayList of our own class type, containing fields like roll no, name, addres
6 min read
Sorting Elements of Arrays and Wrapper Classes that Already Implements Comparable in Java
Java provides the Comparable interface to sort objects using data members of the class. The Comparable interface contains only one method compareTo() that compares two objects to impose an order between them. It returns a negative integer, zero, or positive integer to indicate if the input object is less than, equal to, or greater than the current
4 min read
Implement PriorityQueue through Comparator in Java
Prerequisite : Priority Queue, Comparator Priority Queue is like a regular queue, but each element has a "priority" associated with it. In a priority queue, an element with high priority is served before an element with low priority. For this, it uses a comparison function which imposes a total ordering of the elements. The elements of the priority
3 min read
TreeSet comparator() Method in Java with Examples
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. The comparato
3 min read
PriorityQueue comparator() Method in Java
The java.util.PriorityQueue.comparator() method shares an important function of setting and returning the comparator that can be used to order the elements in a PriorityQueue. The method returns a null value if the queue follows the natural ordering pattern of the elements.Syntax: comp_set = (PriorityQueue)Priority_Queue.comparator() Parameters: Th
2 min read
PriorityBlockingQueue comparator() method in Java
The comparator() method of PriorityBlockingQueue returns the comparator that can be used to order the elements in a PriorityBlockingQueue. The method returns null value if the queue follows the natural ordering pattern of the elements. Syntax: public Comparator<? super E> comparator() Returns: This method returns the comparator set used to or
2 min read
TreeMap comparator() method in Java with Examples
The comparator() method of java.util.TreeMap class is used to return the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys. --> java.util Package --> TreeMap Class --> comparator() Method Syntax: public Comparator comparator() Return Type: This method returns the comparator used to ord
2 min read
SortedMap comparator() method in Java with Examples
The comparator() method of java.util.SortedMap interface is used to return the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.Syntax: public Comparator comparator() Return Value: This method returns the comparator used to order the keys in this map, or null if this map uses the natural order
2 min read
ConcurrentSkipListSet comparator() method in Java with Examples
The comparator() method of java.util.concurrent.ConcurrentSkipListSet is an in-built function in Java which returns the comparator used for ordering the elements in the given set. If natural ordering is used, null is returned. Syntax: public Comparator<E> comparator() Here E is the type parameter i.e. the type of elements maintained by the se
2 min read
Comparator nullsFirst() method in Java with examples
The nullsFirst(java.util.Comparator) method returns comparator that is a null-friendly comparator and considers null values to be less than non-null. The null first operates by the following logic: The null element is considered to be less than non-null. When both elements are null, then they are considered equal. When both elements are non-null, t
3 min read
Comparator comparingInt() in Java with examples
The comparingInt(java.util.function.ToIntFunction) method accepts a function as parameter that extracts an int sort key from a type T, and returns a Comparator that compares by that sort key.The returned comparator is serializable if the specified function is also serializable. Syntax: static <T> Comparator<T> comparingInt(ToIntFunction
3 min read
Comparator nullsLast() method in Java with examples
The nullsLast (java.util.Comparator) method returns comparator that is a null-friendly comparator and considers null values greater than non-null. The null first operates by the following logic: The null element is considered to be greater than non-null. When both elements are null, then they are considered equal. When both elements are non-null, t
3 min read
Comparator thenComparingInt() method in Java with examples
The thenComparingInt(java.util.function.ToIntFunction) method of Comparator Interface in Java returns a lexicographic-order comparator with a function that extracts a int sort key. Syntax: default Comparator <T> thenComparingInt(ToIntFunction <T> keyExtractor) Parameters: This method accepts keyExtractor which is the function used to ex
2 min read
Comparator reverseOrder() method in Java with examples
The reverseOrder() method of Comparator Interface in Java returns a comparator that use to compare Comparable objects in reverse of natural order. The returned comparator by this method is serializable and throws NullPointerException when comparing null. Syntax: static <T extends Comparable<T>> Comparator<T> reverseOrder() Paramet
1 min read
Comparator reversed() method in Java with examples
The reversed() method of Comparator Interface in Java returns a comparator that imposes the reverse ordering of this comparator. If you use sort method of the array and passes this comparator after applying the reversed method then it will sort the array in reverse order. Syntax: default Comparator<T> reversed()Parameters: This method accepts
2 min read
Comparator comparingLong() method in Java with examples
The comparingLong(java.util.function.ToLongFunction) method of Comparator Interface in Java accepts a function as parameter that extracts an long sort key from a type T, and returns a Comparator that compares by that sort key.The returned comparator is serializable if the specified function is also serializable. Syntax: static <T> Comparator
3 min read
Comparator naturalOrder() method in Java with examples
The naturalOrder() method of Comparator Interface in Java returns a comparator that use to compare Comparable objects in natural order. The returned comparator by this method is serializable and throws NullPointerException when comparing null. Syntax: static <T extends Comparable<T>> Comparator<T> naturalOrder() Parameters: This m
1 min read
Comparator thenComparingDouble() method in Java with examples
The thenComparingDouble(java.util.function.ToDoubleFunction) method of Comparator Interface in Java returns a lexicographic-order comparator with a function that extracts a double sort key. This method is applied after comparing method if you want to apply another comparing for those values which are equal in the comparing method. Syntax: default C
3 min read
Comparator comparingDouble() method in Java with examples
The comparingDouble(java.util.function.ToDoubleFunction) method of Comparator Interface in Java accepts a function as parameter that extracts an double sort key from a type T, and returns a Comparator that compares by that sort key.The returned comparator is serializable if the specified function is also serializable. Syntax: static <T> Compa
3 min read
Comparator thenComparingLong() method in Java with examples
The thenComparingLong(java.util.function.ToLongFunction) method of Comparator Interface in Java returns a lexicographic-order comparator with a function that extracts a Long sort key. Syntax: default Comparator <T> thenComparingLong( ToLongFunction <T> keyExtractor) Parameters: This method accepts keyExtractor which is the function used
2 min read
Sort an Array in Java using Comparator
A Comparator is an object that can be used to compare two objects and determine their order. You can use a Comparator to sort a list of objects in any order you choose, not just in ascending order. Examples:Array(Ascending Order): Input: arr = (4, 2, 5, 1, 3) Output: [1, 2, 3, 4, 5] Array(Descending Order): Input: arr = (4, 2, 5, 1, 3) Output: [5,
4 min read
Why Java Language is Slower Than CPP for Competitive Programming?
Choosing the appropriate language while starting competitive programming is the most important factor. Generally, we choose that language that has short syntax and executes very fast or which is familiar to us, and we know all the working patterns of that particular whether it is Java or C++. Most of the programmers use C++ for competitive programm
5 min read
Why BufferedReader class takes less time for I/O operation than Scanner class in java
In Java, both BufferReader and Scanner classes can be used for the reading inputs, but they differ in the performance due to their underlying implementations. The BufferReader class can be generally faster than the Scanner class because of the way it handles the input and parsing. This article will guide these difference, provide the detailed expla
3 min read
Why does Java's hashCode() in String use 31 as a multiplier?
How hashing is done? A hash works by allocating a value into one of the many storage spaces it has, allowing for fast retrieval later. This storage space is also known as buckets. Hash identifies where to insert which data and that also hash tells in constant time in which bucket the value is stored. Problems with Hash: Now though hashing has the b
3 min read
Why to use char[] array over a string for storing passwords in Java?
1. Strings are immutable: Strings are immutable in Java and therefore if a password is stored as plain text it will be available in memory until Garbage collector clears it and as Strings are used in the String pool for re-usability there are high chances that it will remain in memory for long duration, which is a security threat. Strings are immut
2 min read
Practice Tags :