Comparator vs Comparable in Java
Jashwanth Jampala
Software Engineer @ People Tech Group | Java Full-Stack Developer | Java , Spring Boot, Microservices, Python, React, SQL, NoSQL, AWS | Open to New Opportunities
Comparable?is used at the?class level in Java, while Comparator is used at the object level.
? Comparable (Class-Level)
?? 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)
?? 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
SWE @ People Tech Group Inc
3 周good work jashwanth