Comparator vs Comparable in Java


Comparable?is used at the?class level in Java, while Comparator is used at the object level.

? Comparable (Class-Level)

  • Implements Comparable<T> inside the class.
  • Uses the internal method compareTo(T o).
  • Return Type: int (0 if equal, positive if greater, negative if smaller).
  • Parameter: One object (T o).
  • Defines a natural ordering.
  • Swapping happens when compareTo() returns > 0.

?? Example:

class Student implements Comparable<Student> {  
    int id;  
    String name;  

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

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

? Comparator (Object-Level)

  • Uses Comparator<T> as an external method.
  • Uses the internal method compare(T o1, T o2).
  • Return Type: int (same as Comparable).
  • Parameter: Two objects (T o1, T o2).
  • Defines custom sorting.
  • Swapping happens when compare() returns > 0.

?? Example:

import java.util.Comparator;  

class StudentNameComparator implements Comparator<Student> {  
    @Override  
    public int compare(Student s1, Student s2) {  
        return s1.name.compareTo(s2.name);  
    }  
}
        

?? Check my GitHub for full implementation: [GitHub link]

#Java #Comparator #Comparable #Sorting #Coding #Collections

Jayasimha Reddy Kanukuntla

SWE @ People Tech Group Inc

3 周

good work jashwanth

要查看或添加评论,请登录

Jashwanth Jampala的更多文章

  • Spring Framework

    Spring Framework

    As Java developers, we constantly seek ways to write cleaner, more efficient code. The Spring Framework (stable version…

    2 条评论
  • Hibernate

    Hibernate

    In modern Java development, managing database interactions efficiently is crucial. Spring Data JPA, a powerful…

  • JDBC

    JDBC

    ?? Why You Should Still Learn Core JDBC in the Era of Spring Data JPA Nowadays, developers rely heavily on Spring Data…

    1 条评论
  • Introduction to Java Predefined Functional Interfaces

    Introduction to Java Predefined Functional Interfaces

    Hi everyone! Today, I’m excited to discuss some of the predefined functional interfaces in Java that are commonly used…

    4 条评论

社区洞察