Comparable vs Comparator in Java
Comparable vs Comparator in Java
Java provides two interfaces to sort objects using data members of the class:
1) Comparable
2) Comparator
Comparator
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.
public int compare(Object obj1, Object obj2):
class Sortbyname implements Comparator<Student> {
// Method
// Sorting in ascending order of name
public int compare(Student a, Student b) {
return a.name.compareTo(b.name);
}
}
Comparable
A comparable object is capable of comparing itself with another object.
class Movie implements Comparable<Movie>{
public int compareTo(Movie m) {
return this.year - m.year;
}
}
using comparator we were able to use different attributes.
using comparable we can use only one comparison.
Comments
Post a Comment