See Example:
public class Student {
private String studentName;
private int rollNo;
private int studenTage;
public Student(int rollNo) {
super();
this.rollNo= rollNo;
}
public Student(int rollNo,String studentName, int studenTage) {
super();
this.studentName= studentName;
this.rollNo= rollNo;
this.studenTage= studenTage;
}
public Student(String studentName, int studenTage) {
super();
this.studentName= studentName;
this.studenTage= studenTage;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public int getStudenTage() {
return studenTage;
}
public void setStudenTage(int studenTage) {
this.studenTage = studenTage;
}
@Override
public String toString() {
return "Student [rollNo=" + rollNo + "]";
}
}
- we Just called the sort method on an ArrayList of Objects which actually doesn’t work until unless we use interfaces like
Comparable
andComparator
.- Now you must have understood the importance of these interfaces. Let’s see how to use them to get the sorting done in our way.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import ArrayListBasic.Student;
public class Detail {
public static void main(String[] args) {
ArrayList<Student> arraylist = new ArrayList<Student>();
arraylist.add(new Student(007, "Item7", 107));
arraylist.add(new Student(006, "Item6", 126));
arraylist.add(new Student(001, "Item1", 121));
arraylist.add(new Student(005, "Item5", 125));
arraylist.add(new Student(003, "Item3", 103));
arraylist.add(new Student(002, "Item2", 122));
System.out.println("Arraylist Object1 : ");
// Collections.sort(arraylist); //error
// if you try to run this statement it will error
// because he generic method sort(List<T>) of type Collections is not applicable
// for the arguments (ArrayList<Student>). The inferred type Student is not a valid substitute
// for the bounded parameter <T extends Comparable<? super T>>
for(Student student : arraylist){
System.out.println(student);
}
// System.out.println("Sort Arraylist Object : ");
System.out.println("Sort Arraylist Object2 Comparator : ");
//Comparable ArrayList Object
Collections.sort(arraylist, new Comparator<Student>() {
@Override
public int compare(Student student1, Student student2) {
return student1.getStudentName().compareTo(student2.getStudentName());
}
});
for(Student student : arraylist){
System.out.println(student);
}
}
}
//result
Arraylist Object1 :
Student [rollNo=7]
Student [rollNo=6]
Student [rollNo=1]
Student [rollNo=5]
Student [rollNo=3]
Student [rollNo=2]
Sort Arraylist Object2 Comparator :
Student [rollNo=1]
Student [rollNo=2]
Student [rollNo=3]
Student [rollNo=5]
Student [rollNo=6]
Student [rollNo=7]
EmoticonEmoticon