public interface Comparable<T>
This interface imposes a total ordering on the objects of each class that implements it.
Comparable interface is used to order the objects of the user-defined class.
It has only one method named compareTo(Object)
. This method provides a single sorting sequence.
List of objects that implement this interface can be sorted automatically by Collections.sort(and Arrays.sort)
.
Can be also used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.
public int compareTo(Object obj)
(compare the current object with the specified object.)
Sorting for:
1. String objects
2. Wrapper class objects
3. User-defined class objects
class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
public int compareTo(Student st){
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}
import java.util.*;
public class TestSort{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(3,"Adam",23));
al.add(new Student(2,"Jae",27));
al.add(new Student(1,"Su",21));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
1 Su 21
3 Adam 23
2 Jae 27
Depending on the sort order (reverse or forward), change the condition for comparing age statement. (ex: if(age > st.age) return 1)