Java provides the Comparable interface, which contains only one method, called compareTo. This method compares two objects, in order to impose an order between them. Specifically, it returns a negative integer, zero, or a positive integer to indicate that the input object is less than, equal or greater than the existing object.
Comparable interface is used to order the objects of user-defined class.This interface is found in java.lang package and contains only one method named compareTo(Object).It provide only single sorting sequence i.e. you can sort the elements on based on single data member only.For instance it may be either rollno,name,age or anything else.
Here I am creating a sample of sorting using Comparable interface in java.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
class Sample {
@SuppressWarnings("unchecked")
public static void main(String args[]) {
// create object of Mathematical class
ArrayList myList = new ArrayList();
myList.add(new Student(101, "Zack", 22));
myList.add(new Student(104, "Anderson", 26));
myList.add(new Student(103, "Joolie", 24));
myList.add(new Student(106, "Raakel", 28));
myList.add(new Student(105, "Abbas", 23));
myList.add(new Student(102, "Ukrit", 21));
myList.add(new Student(108, "Abbe", 29));
myList.add(new Student(107, "1234", 29));
Collections.sort(myList);
Iterator<Student> iter = myList.iterator();
System.out.println("Sorting by UserId\n");
while (iter.hasNext()) {
Student student = (Student) iter.next();
System.out.println(student.sId + " " + student.Sname);
}
}
}
class Student implements Comparable {
int sId;
String Sname;
int age;
public Student(int id, String name, int age) {
this.sId = id;
this.Sname = name;
this.age = age;
}
public int compareTo(Object obj) {
Student st = (Student) obj;
if (sId == st.sId)
return 0;
else if (sId > st.sId)
return 1;
else
return -1;
}
}
Output-:
Sorting by UserId
101 Zack
102 Ukrit
103 Joolie
104 Anderson
105 Abbas
106 Raakel
107 1234
108 Abbe
Samuel Fernandes
23-Apr-2015